This is the 28th day of my participation in the August Text Challenge.More challenges in August
preface
Eat enough to write code
Today’s look at JSON(JavaScript Object Notation), a strict subset of JavaScript that uses several patterns in JavaScript to represent structured data. The key to understanding JSON is to think of it as a data format, not a programming language. It doesn’t belong in JavaScript, it just shares the same syntax, and it’s not unique to JavaScript, it’s a universal data format, and many languages have built-in capabilities to parse and serialize JSON.
grammar
JSON syntax supports three types:
- Simple values
Strings, values, booleans, and null can appear in JSON, but undefined cannot.
- object
The first complex data type represents an ordered key-value pair, where each value can be a simple value or a complex type.
- An array of
The second kind of complex data types, it can be accessed through numerical index value of orderly queue, its value can be any type, including simple values, objects or even other JSON array variables, the concept of function or object instance, JSON all mark just for structured data, although it borrowed from the syntax of JavaScript, But be careful not to confuse it with the JavaScript language.
Simple values
Such as:
6 // This JSON represents the value 5
"Hello World!" // This represents a JSON string.
Copy the code
Booleans and NULL are valid JSON values in their own right, but in practice it is common to use complex data structures where simple values are used.
object
Such as:
// Object literals in JavaScript
let person = {
name = "Tom",
age = 29
};
// Objects in JavaScript
{
"name" = "Tom"."age" = 29
}
Copy the code
JSON objects differ from JavaScript objects in two ways:
- No variable declaration
- No semicolons at the end (because it’s not a JavaScript statement)
Note: Object attribute names in JSON must always be enclosed in double quotes, and it is a common mistake to omit these or write them as single quotes when writing JSON manually.
An array of
// Object literals in JavaScript
let arr = [25.'hi'.true];
/ / the JSON array
[25.'hi'.true]
// JSON can be combined with objects[{"name" = "Spring"."author" = "zhangsan"
},
{
"name" = "Summer"."author" = "lisi"}]Copy the code
parsing
JSON’s rapid popularity is largely due to the fact that it can be parsed directly into usable JavaScript objects, as in the example above
book[1].name// Get the name of the second book
Copy the code
Traversing the DOM structure is complicated by comparison
doc.getElementsByTagName("book") [1].getAttribute("name");
Copy the code