Those points of knowledge about JSON

Source: Internet
Author: User
Tags tojson

Previous words

The full name of the JSON (JavaScript Object notation) is the representation of JavaScript objects, which is a text format for data exchange and not a programming language for reading structured data. The 2001 was proposed by Douglas Crockford to replace the cumbersome and cumbersome XML format. This article will detail the contents of JSON

Grammar rules

The syntax of JSON can represent the following three types of values

"1" Simple value

Simple values use the same syntax as JavaScript to represent strings, numeric values, Booleans, and Null in JSON

The string must be in double quotation marks and cannot use single quotation marks. Values must be expressed in decimal, and Nan and infinity cannot be used

Note JSON does not support special values in JavaScript undefined

Qualified simple value 5 "Hello World" truenull
Unqualified simple value +0x1 ' Hello World ' undefinednaninfinity

"2" Object

An object is a complex data type that represents an ordered set of key-value pairs. The value of each key-value pair can be a simple value, or it can be a value of a complex data type

JSON has three different places compared to the object literals of JavaScript

1, JSON does not have the concept of variables

2. In JSON, the key name of the object must be enclosed in double quotation marks

3, because JSON is not a JavaScript statement, so there is no end of the semicolon

[note] Two properties with the same name should not appear in the same object

Qualified object {    "name": "Huochai", "Age": "    School": {        "name": "Diankeyuan", "Location": "        Beijing"    }}
Unqualified Object {name: ' Zhang San ', ' age ': 32}//Property name must use double quotation marks {};//does not require the end of the semicolon {"Birthday": New Date (' Fri, 07:13:10 GMT '),  "ge Tname ": function () {      return this.name;  }}//cannot use functions and date objects

"3" Array

An array is also a complex data type that represents a list of ordered sets of values that can be accessed by a numeric index. The value of an array can also be any type-simple value, object, or array

JSON arrays also have no variables and semicolons, which combine arrays and objects to form more complex collections of data

[note] After the last member of an array or object, you cannot add commas

JSON object

JSON is popular because JSON data structures can be parsed into useful JavaScript objects

ECMAScript5 the behavior of parsing JSON, defines the global object json

Note Ie7-Browser does not support

There are two methods of JSON objects: Stringify () and parse (). These two methods are used to serialize JavaScript objects into JSON strings and to parse JSON strings into native JavaScript values

Stringify ()

The Json.stringify () method is used to convert a value to a string. The string should be in JSON format and can be restored by the Json.parse () method

By default, the JSON string for the json.stringify () output does not include any space characters or indents

var jsonobj = {    "title": "JavaScript",    "group": {        "name": "Jia",        "tel": 12345    }};//{"title": " JavaScript "," group ": {" name ":" Jia "," tel ": 12345}}json.stringify (Jsonobj);

Specific conversions

Json.stringify (' abc ')//"" ABC "" Json.stringify (1)//"1" json.stringify (FALSE)//"false" json.stringify ([])//"[]" Json.stringify ({})//"{}" json.stringify ([1, "false", false])//' [1, ' false ', false] ' json.stringify ({name: "Zhang San"})//' {" Name ":" Zhang San "} '

The Stringify () method converts regular expressions and mathematical objects into string forms of empty objects

Json.stringify (/foo/)//"{}" Json.stringify (Math)//"{}"

The Stringify () method converts a Date object and wrapper object to a string

Json.stringify (New Boolean (TRUE))//"True" json.stringify (new String (' 123 '))//"" 123 "" Json.stringify (new Number (1))/ /"1" json.stringify (new Date ())//"" 2016-09-20t02:26:38.294z ""

If the member of the object is a undefined or function, this member is omitted

If the members of the array are undefined or functions, the values are converted to NULL

Json.stringify ({  a:function () {},  b:undefined,  C: [function () {}, undefined]});//"{" C ": [Null,null]}"

The Json.stringify () method ignores the object's non-traversal properties

var obj = {};object.defineproperties (obj, {  ' foo '): {    value:1,    enumerable:true  },  ' bar ': {    Value:2,    enumerable:false  }}); Json.stringify (obj); {"Foo": 1}]

Parameters

Json.stringify () In addition to the JavaScript object to serialize, you can also receive two additional parameters, which are used to specify a different way to serialize the JavaScript object. The first parameter is a filter, which can be an array or a function, and the second argument is an option that indicates whether the indentation is preserved in the JSON string

"Array Filter"

When the second parameter of the Stringify () method is an array, this is equivalent to implementing a filter function

The "1" filter is valid only for the first-level property of an object

var jsonobj = {    "title": "JavaScript",    "group": {        "a": 1    }};//{"group": {"a": 1}}console.log ( Json.stringify (jsonobj,["group", "a"]))

"2" Filter Invalid array

var jsonobj =[1,2]; Json.stringify (jsonobj,["0"])//"[Up]"

"Function Parameter"

The second parameter of the Stringify () method can also be a function. The incoming function receives two parameters, the property (key) name and the property value

Json.stringify ({a:1,b:2}, function (key, value) {  if (typeof value = = = "Number") {    value = 2 * value;  }  return value;    }) "{" A ": 2," B ": 4}"

The property name can be a string only, and the key name may be an empty string when the value is not a value of a key-value pair structure

This function parameter recursively handles all keys.

In the following code, the object o will be processed three times by the F function altogether. The first key name is NULL, the key value is the entire object o; the second key name is a, the key value is {b:1}, the third key is named B, the key value is 1

Json.stringify ({A: {b:1}}, function (key, value) {  console.log ("[" + Key + "]:" + value);  return value;}) []:[object object]//[A]:[object object]//[b]:1//' {"a": {"B": 1}} '    

The value returned by the function is the value of the corresponding key. If the function returns undefined or no return value, the corresponding property is ignored

Json.stringify ({A: "abc", B:123}, function (key, value) {  if (typeof (value) = = = "string") {    return undefined;
   }  return value;}) ' {' B ': 123} '

"Indent"

The Stringify () method can also accept the third parameter to increase the readability of the returned JSON string

If it is a number, the space (up to 10) that is added before each property

If it is a string (no more than 10 characters), the string is added in front of each line

/* "{  " P1 ": 1,  " P2 ": 2}" */json.stringify ({p1:1, p2:2}, NULL, 2);
"{" P1 ": 1," P2 ": 2}" Json.stringify ({p1:1, p2:2}, NULL, 0);
/* "{|" P1 ": 1,|-" P2 ": 2}" */json.stringify ({p1:1, p2:2}, NULL, ' | ');

ToJSON ()

Sometimes, json.stringify () does not satisfy the need for custom serialization of certain objects. In these cases, you can call the Tojson () method on the object to return its own JSON data format

Json.stringify ({  tojson:function () {    return "cool"  }})//"Cool" "
var o = {  foo: ' foo ',  tojson:function () {    return ' bar ';  }}; Json.stringify ({x:o});//' {"X": "Bar"} '

If the Tojson () method returns undefined, it causes the value of the object to become null if it is embedded in another object. And if the object that contains it is a top-level object, the result is undefined

Json.stringify ({  tojson:function () {    return undefined  }})//undefined

The Date object deploys its own Tojson method to automatically convert a Date object to a day string

Json.stringify (New Date ("2016-08-29"))//"2016-08-29t00:00:00.000z"

One application of the Tojson method is that the regular object can be automatically converted to a string

RegExp.prototype.toJSON =regexp.prototype.tostring; Json.stringify (/foo/)//"/foo/" "

ToJSON () can be supplemented as a function filter, so it is important to understand the internal order of serialization. Suppose you pass an object into Json.stringify () and serialize the object in the following order

1. If there is a Tojson () method and can get a valid value through it, the method is called. Otherwise, the serialization is performed in the default order

2, if the second parameter is provided, apply this function filter. The value passed into the function filter is the value returned in the first step

3, the corresponding serialization of each value returned in the second step

4, if the third parameter is provided, the corresponding formatting is performed

Parse ()

The Json.parse method is used to convert a JSON string into an object

Json.parse (' {} ')//{}json.parse (' true ')//Truejson.parse (' "foo")//"foo" Json.parse (' [1, 5, ' false '] ')//[1, 5, "false "]json.parse (' null ')//Nullvar o = Json.parse (' {" name ":" Zhang San "} '); O.name//Zhang San

If the passed-in string is not a valid JSON format, the Json.parse method will error

Uncaught syntaxerror:unexpected token u in JSON at position 0 (...) Json.parse ("' String '")//uncaught syntaxerror:unexpected token u in JSON at position 0 (...) Json.parse ("undefined")

The Json.parse () method can also receive a function parameter, called on each key-value pair, which is called the Restore function (reviver). The function receives two parameters, a key and a value, and returns a value

If the Restore function returns undefined, the corresponding key is removed from the result, and if another value is returned, the value is inserted into the result

var o = json.parse (' {"A": 1, "B": 2} ', function (key, value) {  if (key = = = ') {    return value;  }  if (key = = = ' A ') {    return value + Ten;  }}); O. A//11O.B//undefined

A restore function is often used when converting a date string to a data date object

var book = {    "title": "JavaScript",    "date": The new Date (2016,9,1)}var jsonstr = json.stringify (book);//' {"" title ":" JavaScript "," date ":" 2016-09-30t16:00:00.000z "} ' Console.log (jsonstr) var bookcopy = Json.parse (Jsonstr,function ( Key,value) {    if (key = = ' Date ') {        return new date (value);    }    return value;}) Console.log (BookCopy.date.getFullYear ());//2016
Eval ()

In fact, Eval () is similar to the Json.parse () method, where you can convert a JSON string to a JSON object

Eval (' (' + ' {"A": 1} ' + ') '). A;//1json.parse (' {"A": 1} '). a;//1

However, Eval () can execute code that is not in JSON format and may contain malicious code

Eval (' (' + ' {' A ': Alert (1)} ' + ') '). a;//popup 1json.parse (' {' A ': Alert (1)} '). a;//error

So, try to use as little as possible eval ()

-Reprint

Those points of knowledge about JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.