首页 > 代码库 > JSON_in_js

JSON_in_js

parse [pɑ:rs]  从语法上描述或分析(词句等),解析

fetch [f?t?]vt.接来(某人);使发出;吸引;拿取 vi.取来;抵达,到达  Using JSON: Fetch a JSON string,JSON.Parse the JSON string

notation [no??te??n]n.记号,标记法  bracket ([]) notation,dot (.) notation, curly braces {}

https://www.w3schools.com/js/js_json_intro.asp

国内:http://w3schools.bootcss.com/json/default.html (比较老的内容,镜像)

JSON vs XML:https://www.w3schools.com/js/js_json_xml.asp

 

---------------------------------------------------------------------------------------------------------

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is "self-describing" and easy to understand
  • JSON is language independent *

*JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.

 

The JSON syntax is a subset of the JavaScript syntax.


JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example

"name":"John"

 

 

JSON - Evaluates to JavaScript Objects

The JSON format is almost identical to JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON

{ "name":"John" }

In JavaScript, keys can be strings, numbers, or identifier names:

JavaScript

{ name:"John" }

 

JSON Uses JavaScript Syntax

Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript.

With JavaScript you can

create an object and assign data to it, like this:   var person = { "name":"John", "age":31, "city":"New York" };

 modifiedt, like this:                                  myObj["name"] = "Gilbert";  or myObj.name = "Gilbert";

<!DOCTYPE html>
<html>
<body>
<p>Modify a JavaScript object using the bracket notation:</p>
<p id="demo"></p>
<script>
var myObj, x;
x = {age:31}
myObj = { "name":"John", "age":30, "city":"New York" };
myObj["name"] = "Gilbert";
myObj.age = x.age;
myObj.city = "LA";
document.getElementById("demo").innerHTML = myObj.name+"  age  "+myObj.age+"  from  "+myObj.city;
</script>
</body>
</html>

 

 

 

-----------------------------------------------

JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:

JSON.parse()

https://www.w3schools.com/js/tryit.asp?filename=tryjson_store

<!DOCTYPE html>
<html>
<body>

<h2>Store and retrieve data from local storage.</h2>

<p id="demo"></p>

<script>
var myObj, myJSON, text, obj;

//Storing data:
myObj = { "name":"John", "age":31, "city":"New York" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

//Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
</script>

</body>
</html>

====================================================================================================================================

JavaScript Arrays as JSON

The same way JavaScript objects can be used as JSON, JavaScript arrays can also be used as JSON.

JSON Files

  • The file type for JSON files is ".json"
  • The MIME type for JSON text is "application/json"

Using JSON

  • Fetch a JSON string
  • JSON.Parse the JSON string

===JSON Data Types ===================================================

Valid Data Types

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON values cannot be one of the following data types:

  • a function
  • a date
  • undefined

JSON Strings

Strings in JSON must be written in double quotes.

Example

{ "name":"John" }

JSON Numbers

Numbers in JSON must be an integer or a floating point.

Example

{ "age":30 }

JSON Objects

Values in JSON can be objects.

Example

{
"employee":{ "name":"John", "age":30, "city":"New York" }
}

Objects as values in JSON must follow the same rules as JSON objects.

===JSON Objects=======================================================================================


Object Syntax

Example

{ "name":"John", "age":30, "car":null }

JSON objects are surrounded by curly braces {}.

JSON objects are written in key/value pairs.

Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).

Keys and values are separated by a colon.

Each key/value pair is separated by a comma.


Accessing Object Values

You can access the object values by using dot (.) notation:

Example

myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;

You can also access the object values by using bracket ([]) notation:

Example

myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];

 

Looping an Object

You can loop through object properties by using the for-in loop:

Example

myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x+"<br>";;
}

In a for-in loop, use the bracket notation to access the property values:

Example

myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += myObj[x]+"<br>";;
}
<!DOCTYPE html>
<html>
<body>
<p>How to loop through all properties in a JSON object.</p>
<p id="demo"></p>
<script>
var myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x + "<br>";
}
</script>
</body>
</html>

 


Nested JSON Objects

Values in a JSON object can be another JSON object.

Example

myObj = {
    "name":"John",
    "age":30,
    "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Fiat"
    }
 }

You can access nested JSON objects by using the dot notation or bracket notation:

Example

x = myObj.cars.car2;
//or:
x = myObj.cars["car2"];

Modify Values

You can use the dot notation to modify any value in a JSON object:

Example

myObj.cars.car2 = "Mercedes";

You can also use the bracket notation to modify a value in a JSON object:

Example

myObj.cars["car2"] = "Mercedes";

Delete Object Properties

Use the delete keyword to delete properties from a JSON object:

Example

delete myObj.cars.car2;

===JSON Arrays====================================================

Arrays as JSON Objects

Example

[ "Ford", "BMW", "Fiat" ]

Arrays in JSON are almost the same as arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean or null.

In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.


Arrays in JSON Objects

Arrays can be values of an object property:

Example

{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}

Accessing Array Values

You access the array values by using the index number:

Example

x = myObj.cars[0];

Looping Through an Array

You can access array values by using a for-in loop:

Example

for (i in myObj.cars) {
    x += myObj.cars[i];
}

Or you can use a for loop:

Example

for (i = 0; i < myObj.cars.length; i++) {
    x += myObj.cars[i];
}

 

Nested Arrays in JSON Objects

Values in an array can also be another array, or even another JSON object:

Example

myObj = {
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }

To access arrays inside arrays, use a for-in loop for each array:

Example

for (i in myObj.cars) {
    x += "<h1>" + myObj.cars[i].name + "</h1>";
    for (j in myObj.cars[i].models) {
        x += myObj.cars[i].models[j];
    }
}

Modify Array Values

Use the index number to modify an array:

Example

 myObj.cars[1] = "Mercedes";

Delete Array Items

Use the delete keyword to delete items from an array:

Example

delete myObj.cars[1];
 

===JSON.parse()=============================================================


A common use of JSON is to exchange data to/from a web server.

When receiving data from a web server, the data is always a string.

Parse the data with JSON.parse(), and the data becomes a JavaScript object.


Example - Parsing JSON

Imagine we received this text from a web server:

‘{ "name":"John", "age":30, "city":"New York"}‘

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

var obj = JSON.parse(‘{ "name":"John", "age":30, "city":"New York"}‘);

Make sure the text is written in JSON format, or else you will get a syntax error.

Use the JavaScript object in your page:

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

JSON From the Server

You can request JSON from the server by using an AJAX request

As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.

Example

Use the XMLHttpRequest to get data from the server:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

Take a look at json_demo.txt


 

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

Example

The JSON returned from the server is an array:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myArr = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myArr[0];
    }
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();

Take a look at json_demo_array.txt


Exceptions

Parsing Dates

Date objects are not allowed in JSON.

If you need to include a date, write it as a string.

You can convert it back into a date object later:

Example

Convert a string into a date:

var text = ‘{ "name":"John", "birth":"1986-12-14", "city":"New York"}‘;
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;

Or, you can use the second parameter, of the JSON.parse() function, called reviver.

The reviver parameter is a function that checks each property, before returning the value.

Example

Convert a string into a date, using the reviver function:

var text = ‘{ "name":"John", "birth":"1986-12-14", "city":"New York"}‘;
var obj = JSON.parse(text, function (key, value) {
    if (key == "birth") {
        return new Date(value);
    } else {
        return value;
    }});

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;

Parsing Functions

Functions are not allowed in JSON.

If you need to include a function, write it as a string.

You can convert it back into a function later:

Example

Convert a string into a function:

var text = ‘{ "name":"John", "age":"function () {return 30;}", "city":"New York"}‘;
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();

You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.


Browser Support

The JSON.parse() function is included in all major browsers and in the latest ECMAScript (JavaScript) standard:

Web Browsers Support
  • Firefox 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4

For older browsers, a JavaScript library is available at https://github.com/douglascrockford/JSON-js.

JSON_in_js