JSON series------(i) initial JSON

Source: Internet
Author: User
Tags tojson

1. What is JSON

JSON, the full name is JavaScript Object Notation, which is the JavaScript objects tagging method. This is a lightweight (light-weight), text-based (text-based), readable (human-readable) format.

JSON has JavaScript in its name, but this means that its syntax rules refer to JavaScript objects, not only to JavaScript languages. In fact, many languages (such as C + +, Java, PHP, and so on) are equipped with JSON parsing and generators.

JSON is very easy to read and write for both people and machines, and the file is smaller than XML (another common data interchange format), so it quickly becomes a popular interchange format on the Web.

2. Syntax rules for JSON
    1. Arrays (array) are expressed in square brackets ("[]").
    2. Objects (object) are represented by curly braces ("{}").
    3. Name/value pairs (Name/value) are separated by a colon (":").
    4. The name (name) is placed in double quotation marks, with values (value) that are string, numeric, Boolean, null, object, and array.
    5. The data is delimited by commas (",")
    6. The value of each member of an array or object, either a simple value or a composite value

It is important to note that empty arrays and empty objects are qualified JSON values, and null itself is also a qualified JSON value.

Simple case:

// a case of describing student information {    "name": "Zhangsan",    "age": +,    "sex": "Male",    "class": " Computer Science ",    " Studentnumber ":" 20120101 ",    course:[    {courseno:" 2015001 "," Coursename ":" Data Structure ", teachername": "Lisi"},    {courseno:"2015002", "Coursename": "Database Principle", TeacherName ":" Wangwu "}    ]}
3. JSON and XML

JSON is often taken to compare with XML, since the birth of JSON is more or less the meaning of replacing XML. The advantages compared to Xml,json are as follows:

    • No end tag, shorter length, faster read and write
    • Can be parsed directly by the JAVASCRIPT interpreter
    • You can use an array

Here are the XML files and JSON files that describe the same information to see the difference. Json:

{    "name": "Geoff Lui",    "age": +,    true,    "Friends": [" Lucy "," Lily "," Gwen "]}

Xml:

<Root>    <name>Geoff Lui</name>    < Age>Geoff Lui</ Age>    <Friends>Lucy</Friends>    <Friends>Lily</Friends>    <Friends>Gwen</Friends></Root>

As you can see, XML is more cumbersome to describe the same information, and JSON is much lighter and more noticeable in the presence of arrays. Moreover, when there are many items in an array, much of the information in the XML file is used to describe the label that is useless.

However, it is not to say that XML is useless, to completely abandon, in the final analysis, it depends on what kind of development requirements.

4.JSON objects

Processes data in JSON format. It has two methods:json.stringify and Json.parse.

4.1,stringify ()

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

Json.stringify ("somestring")//"somestring"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 '} '

It is important to note that for the original type of string, the result of the conversion will be double quotes, that is, the string somestring will be converted "somestring" , because in the future, double quotes can let the JavaScript engine know that ABC is a string, not a variable name.

If the original object has a member with a value of undefined, a function, or an XML object, this member is omitted. If the members of the array are undefined, functions, or XML objects, the values are converted to NULL.

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

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

var obj = {};object.defineproperties (obj, {  ' foo '):    {1,    True    },  ' bar ': {    2,    false  //  {"foo": 1}

The Json.stringify method can also accept an array parameter, specifying a property that needs to be converted to a string.

Console.log (json.stringify ({name: "Zhangsan", age:22}, [' Name ']));         //   {"name": "Zhangsan"}

The Json.stringify method can also accept a function as a parameter to change the default string behavior.

function f (Key, value) {  if (typeof value = = = "Number") {    = 2 * value;  }   return  value;} Json.stringify ({A:1, B:2 }, f)//  ' {"A": 2, "B": 4} '

Json.stringify can also accept the third parameter, which increases the readability of the returned JSON string. If it is a number, the space (up to 10) is added before each property, and if it is a string (no more than 10 characters), the string is added in front of each line.

null, 2); // "{  " P1 ": 1,  " P2 ": 2}"|| "{|-" P1 ": 1,| -"P2": 2}"

If the Json.stringify method handles an object that contains a Tojson method, it uses this method to get a value and then turns the value into a string, ignoring the other members.

json.stringify ({  function() {    return "Cool"  }})//  "Cool" "var o = {  ' foo ',  function() {     return ' Bar ';  }; var json =//  ' {"x": "Bar"} '

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

4.2. Json.parse ()

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

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

If the passed-in string is not a valid JSON format, the Json.parse method will error. In order to handle parsing errors, you can place the Json.parse method in a Try...catch code block.

The Json.parse method can accept a handler function similar to the Json.stringify method.

function f (Key, value) {  if (key = = = ")      {return  value  ;  } if (Key = = = "a" ) {    return value + ten;  }} var o = Json.parse (' {"A": 1, "B": 2} '//  ///  undefined 
    1. Reference link: json.parse ()
    2. Nanyi's Tutorials

JSON series------(i) initial 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.