Week7——JSON

1. What is JSON?

  JSON is JavaScript Object Notation, the full name is JavaScript Object Notation. It is a syntax for storing and exchanging textual information, similar to XML. JSON is a lightweight text data interchange format that is self-describing and easier to understand. It is smaller, faster and easier to parse than XML.

  JSON uses JavaScript syntax to describe data objects, but JSON remains language and platform independent. JSON parsers and JSON libraries support many different programming languages.

2. Similarities and differences with XML?

  Similarities:

  • JSON is plain text
  • JSON is "self-describing" (human readable)
  • JSON has a hierarchical structure (values ​​exist within values)
  • JSON can be parsed by JavaScript
  • JSON data can be transferred using AJAX

  the difference:

  • no closing tag
  • Shorter
  • Read and write faster
  • Ability to parse using the built-in JavaScript eval() method
  • use an array
  • Do not use reserved words

3. JSON writing format

  JSON data is written in the form of name/value pairs. for example:

  • JSON array
{
"employees": [
    { "firstName":"Bill" , "lastName":"Gates" },
    { "firstName":"George" , "lastName":"Bush" },
    { "firstName":"Thomas" , "lastName":"Carter" }
]
}
  • JSON objects are written in curly braces, and objects can contain multiple name/value pairs:

  { "firstName":"Bill" , "lastName":"Gates" }

  • "firstName":"Bill" This is similar to JavaScript's firstName="Bill". 

4. JSON value

  JSON values ​​can be:

  • number (integer or float)
  • string (in double quotes)
  • logical value (true or false)
  • array (in square brackets)
  • object (in curly braces)
  • null

 

5. Convert to JavaScript Object

  JavaScript string containing JSON syntax: 

var txt = '{ "employees" : [' +
'{ "firstName":"Bill" , "lastName":"Gates" },' +
'{ "firstName":"George" , "lastName":"Bush" },' +
'{ "firstName":"Thomas" , "lastName":"Carter" } ]}';

  The JavaScript function eval() can be used to convert JSON text to JavaScript objects. The eval() function uses a JavaScript compiler that parses JSON text and produces JavaScript objects. The text must be enclosed in parentheses to avoid syntax errors:  

var obj = eval ("(" + txt + ")");

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691144&siteId=291194637