JSON object Detailed and instance code _ basics

Source: Internet
Author: User
Tags eval object object serialization tojson

Front.

The full name of the JSON (JavaScript Object notation) is the JavaScript objects notation, a text format for data interchange, not a programming language for reading structured data. Proposed by Douglas Crockford in 2001, the goal is to replace cumbersome and cumbersome XML formats. This article will provide a detailed description of the JSON content

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, which can represent strings, values, Boolean values, and NULL in JSON

Strings must be enclosed in double quotes and cannot be used in single quotes. Values must be in decimal notation, and nan and infinity cannot be used

Attention JSON does not support special values in JavaScript undefined

Qualified simple value
5
"Hello World"
true
null

Unqualified simple value
+0x1
' Hello World '
undefined
NaN
Infinity

"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 a value of a complex data type

JSON has three different places than the object literal of JavaScript

1, JSON does not have the concept of variables

2, in JSON, the object's key name must be placed inside double quotes

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 objects
{
  "name": "Huochai",
  "age": "
  School": {
    "name": "Diankeyuan",
    "location": " Beijing "
  }
}

Unqualified object
{name: ' John ', ' age ': 32}//Property name must use double quotes
{};//does not need a trailing semicolon
{"Birthday": New Date (' Fri, Aug 2011 07:13 : Ten GMT '),
 "GetName": 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 values that can be accessed by a numeric index. The value of an array can also be any type--a simple value, an object, or an array

The JSON array also has no variables and semicolons, combining arrays and objects to form a more complex set of data

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

JSON object

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

ECMAScript5 the behavior of parsing JSON and defines global object JSON

Attention Ie7-Browser does not support

The JSON object has two methods: Stringify () and parse (). These two methods are used to serialize JavaScript objects into JSON strings and 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 whitespace characters or indents

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

Specific conversion

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: ' John '})//' {' name ': ' John '} '

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

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

Stringify () method converts date objects and wrapper objects into strings

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 object's members are undefined or functions, 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 non-traversal properties of the object

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 receive two additional parameters that specify a different way to serialize the JavaScript object. The first argument is a filter that can be an array or a function; The second argument is an option that indicates whether to keep indents 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 works only on the first layer of an object's properties

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"])//"[1,2]"

"Function Parameters"

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}"

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

This function parameter recursively handles all the keys

In the following code, the object o is processed three times by the F function altogether. The first time the key is null, the key value is the whole object o; the second key is a, the key value is {b:1}, the third key is B, and 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 does not return a value, then 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 a third parameter to increase the readability of the returned JSON string

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

If it is a string (no more than 10 characters), the string is added to the 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, then if the object containing it is embedded in another object, it causes the value of the object to become null. 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 a Tojson method of its own to automatically convert the Date object to a date string

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


One application of the Tojson method is that you can automatically convert a regular object to a string

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

Tojson () can be added as a function filter, so it is important to understand the internal order of serialization. Suppose that an object is passed into Json.stringify (), and the order of the object is serialized as follows

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

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

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

4. If you provide a third parameter, perform the appropriate formatting

Parse ()

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

Json.parse (' {} ')//{}
Json.parse (' true ')//True
json.parse (' foo ' ')//' foo '
json.parse (' [1, 5, ' false '] ')//[1, 5, ' false ']
json.parse (' null ')//null
var o = json.parse (' {' name ': ' John '} ');
O.name//John

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 argument, called on each key-value pair, called a restore function (reviver). The function receives two parameters, a key and a value, and returns a value

If the Restore function returns undefined, it means that the corresponding key is to be deleted from the result, and if a different 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 +;
 }
});
O.A//
O.B//UNDEFINEF

You often use a restore function when you convert a date string to date objects

var book = {
  "title": "JavaScript",
  "date": 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, which converts a JSON string to a JSON object

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

However, Eval () can execute code that does not match the JSON format and may contain malicious code

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

So, still try to use Eval () as little as possible.

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.