This note is from W3school and is not comprehensive and should be supplemented in practical applications in the future
Example
<body>
<p>
Name: <span id= "Jname" ></span><br/>
Age: <span id= "Jage" ></span><br/>
Address: <span id= "Jstreet" ></span><br/>
Phone: <span id= "Jphone" ></span><br/>
</p>
<script type= "Text/javascript" >
var jsonobject={
"Name": "Bill Gates",
"Street": "Fifth Avenue New York 666",
"Age": 56,
"Phone": "555 1234567"
};
document.getElementById ("Jname"). Innerhtml=jsonobject.name
document.getElementById ("Jage"). Innerhtml=jsonobject.age
document.getElementById ("Jstreet"). Innerhtml=jsonobject.street
document.getElementById ("Jphone"). Innerhtml=jsonobject.phone
</script>
</body>
comparison with XML
With:
JSON is plain text
JSON has a "self-descriptive" (Human readable)
JSON has a hierarchy (values exist in values)
JSON can be parsed with JavaScript
JSON data can be transmitted using AJAX
Vary
No end tag
Even shorter
Read and write faster
Ability to parse using the built-in JavaScript eval () method
Working with arrays
Do not use reserved words
JSON Syntax
Data in Name/value: "FirstName": "John" <=>firstname= "John"
Data is separated by commas
Curly braces Save Object
Square brackets Save Array
The JSON value can be:
Number: integer or floating point
String: Use double quotation marks to widen.
Logical value: TRUE, False
Array: square brackets wide-{"colors": [{"Name": "Red", "value": "Red"},{"name": "Blue", "value": "Cyan"}]}
Object: Width with curly braces-{"firstName": "John", "LastName":D OE "}
Null
JSON file
The file type of the JSON file is. JSON
The MIME type of the JSON file is Application/json
Convert JSON text to JavaScript object
One of the most common uses of JSON is to read the JSON data from the Web server (as a file or as a HttpRequest), convert the JSON data to a JavaScript object, and then use that data in a Web page. The following uses a string instead of a file as an input demo:
To create a JavaScript object:
var txt= ' {"Employees": [' +
' {' firstName ': ' John ', ' lastName ': ' Doe '}, ' +
' {' firstName ': ' Anna ', ' lastName ': ' Smith '}, ' +
' {' fistname ': ' Peter ', ' lastName ': ' Jones '}]} ';
var obj=eval ("(" +txt+ ")");
To use JavaScript objects in a Web page:
<p>
First Name: <span id= "FName" ></span><br/>
Last Name: <span id= "lname" ></span><br/>
</p>
<script>
document.getElementById ("FName"). Innerhtml=obj.employees[1].firstname
document.getElementById ("LName"). Innerhtml=obj.employees[1].lastname
</script>
"W3s" JSON