JSON initial knowledge

Source: Internet
Author: User
Tags tojson

Reprint website: http://developer.51cto.com/art/201704/536386.htm

Let's take a look at a common JS object in JS serialized into a JSON string problem.

Excuse me: What is the string after the following JS object passed json.stringify?

(Do not rush to copy and paste to the console, first open a code editor or paper, write and read, write, and then carefully compare your console output, if wrong remember to read the full text and comments, haha. )

The second question, if I want to put this ' friend ' name all into uppercase in the final JSON string, that is, "good" into "good", "man" into "man", then what can be done?

Based on the above two questions, let's go back and ask:

    • What exactly is JSON?
    • Why is JSON easy to exchange data?
    • What is the difference between JSON and JS objects?
    • JS in Json.parse, json.stringify and Uncommon Tojson, the parameters of these functions and processing details exactly what?

Welcome to this "deep-digging JSON tour", which will understand JSON in the following ways:

    • The first is the understanding that "JSON is a lightweight data interchange format";
    • Then look at the differences between JSON and JS objects that are often confused;
    • Finally, we look at the specific implementation details of these JSON-related functions in JS.

I hope that the full text can be as I did before the JSON smattering's pro can say what JSON is, but also skilled in using JSON, do not look at the console to know the JS object serialized into a JSON string after the output is what.

JSON is a format

-text-based, better than light weight for exchanging data

If you have not been to the official JSON introduction can go to here, the official introduction of the first to second paragraph has been very clear about what JSON is, I would like to refine the JSON into the following aspects:

1. A data format

What is a format? is to standardize your data how to say, for a chestnut, there is a person called "260", height "160cm", Weight "60kg", now you want to pass this person's information to others or something else, you have a lot of choices:

    • Name "260", height "160cm", Weight "60kg"
    • Name= "260" &height= "160cm" &weight= "60kg"
    • <person><name> 260 </name>
    • {"Name": "260", "height": "Weight": 60}
    • ... ...

All of the above choices, the data passed is the same, but you can see the form can be all kinds of, this is a variety of different formatted data, JSON is one of the means.

2. Text-based data format

JSON is a text-based data format, relative to binary-based data, so JSON is passed as a string that conforms to the JSON format (as far as the JSON format is our second part), which we often call "JSON strings".

3. Lightweight data format

Before JSON, there is a data format called XML, which is still widely used, but JSON is lighter, such as XML requires a lot of tags.

As shown in the example above, you can clearly see that the tags themselves occupy a lot of space in the XML format data, while the JSON is lighter, that is, the same data, the bandwidth in JSON is smaller, which has a significant advantage in the case of large data requests and delivery.

4. Widely used in data exchange

Lightweight is already an advantage for data exchange, but the more important JSON is easy to read, write, and machine parse, meaning that the JSON is friendly to both humans and machines, and is light and language independent (because it is text-based), so JSON is widely used for data exchange.

For example, the back-end PHP processing request is an example of a POST request from the previous-side JS for Ajax:

1). The front-end constructs a JS object that wraps the data to be passed, then converts the JS object into a JSON string and sends the request to the backend;

2). Back-end PHP receives this JSON string, converts the JSON string into a PHP object, and then processes the request.

The front-end constructs a JS object, which wraps the data to be passed, then converts the JS object into a JSON string and sends the request to the backend;

The back-end PHP receives the JSON string, converts the JSON string into a PHP object, and then processes the request.

As you can see, there are 3 different representations of the same data, namely the JS object on the front, the JSON string being transmitted, and the back-end PHP object.

JS object and PHP object is obviously not a thing, but because everyone uses JSON to pass the data, everyone can understand the data format, can be the JSON this data format can easily be translated into their own understanding of the data structure.

This makes it easy to exchange data in a variety of other locales.

"Gossip" between JSON and JS objects

Most of the time you hear "JSON is a subset of JS" This sentence, and this sentence I have always thought, each JSON-formatted string you parse into JS can be, until later found a strange thing ...

1. Two things that are fundamentally different why so closely

JSON and JS objects are not exactly the same thing in nature, like "zebra" and "zebra", "zebra" based on the stripes on the "zebra" to present and name, but the zebra is alive, zebra is non-living.

Similarly, the "JSON" full name "JavaScript object Notation", so its format (syntax) is based on JS, but it is a format, and the JS object is an instance, is a thing that exists in memory.

A joke, if JSON is PHP-based, may be called Pon, the form may be this [' propertyone ' = ' foo ', ' propertytwo ' + 42,], if so, Then JSON might be more closely related to PHP now.

In addition, JSON can be transferred, because it is a text format, but the JS object is not able to transmit, in syntax, JSON will be more strict, but the JS object is very loose.

So two different things why so close, because JSON after all evolved from JS, the syntax is similar.

2.JSON format is more rigorous than JS object syntax

First, the "key-value pairs for the performance of the object" form, compared to the difference between the two, as to how the JSON can also be the form of performance, comparison and then listed.

As you can see, the JSON format is stricter than the JS object, so most of the JS objects are written in a format that is not JSON-compliant.

3.JSON is not a subset of JS

First look at the following code, you can copy to console execution under:

These two characters \u2028 and \u2029 respectively represent the line delimiter and the paragraph delimiter, json.parse can parse normally, but as JS parsing will error.

The JSON functions in these JS

In JS we are mainly exposed to two and JSON-related functions, respectively, for the conversion between the JSON string and the JS data structure.

One is called json.stringify, it is very clever, smart to you write the non-JSON format of the JS object can help you to deal with the JSON format of the string, so you need to know what it did, lest it just smart, and then let you debug long time.

Another is called Json.parse, used to convert the JSON string to the JS data structure, it is very strict, your JSON string if the structure is not correct, there is no way to parse.

And they have more than one parameter, although we often use only one parameter.

In addition, there is a tojson function that we see less, but it affects json.stringify.

1.JS data structures converted to JSON strings

Converts a JS data structure into a JSON string--json.stringify

The function signature for this function is this:

The following will expand the usage of each parameter, and finally the "smart" thing that it does when serializing, pay special attention to it.

1.1 Basic use-only one parameter is required

This everyone will use, pass in a JSON format JS object or array, json.stringify ({"Name": "Good Man", "Age": 18}) return a string "{" Name ":" Good Man "," Age ": 18}".

We can see that the JS object we passed in is a JSON-formatted, double-quote, and no JSON-unacceptable property value, so what do you do to play, as in the example in the beginning?

No hurry, let's start with a simple example to illustrate the meaning of several parameters of the function, and then the problem.

1.2 The second argument can be a function, or it can be an array

    • If the second argument is a function, then each property in the serialization process is transformed and processed by this function
    • If the second argument is an array, only the attributes contained in the array will be serialized into the final JSON string
    • If the second parameter is NULL, it makes no difference between the function and the empty, but does not want to set the second parameter, just want to set the third parameter, you can set the second parameter is NULL

This second argument is a function

If the second parameter is a function, then the function must have a return for each item, which takes two arguments, a key name, and a property value, and the function must have the return of the new property value for each original property value.

So the question is, what if the input is not an object form of a key-value pair, but an array of square brackets?, such as the friend of the above becomes this: friend=["Jack", "Rose", then the property-handling function receives the key and value?

If it is an array, then key is the index value, and value is the array item, and you can print the key and value validation in the console inside the function, remember to return value inside the function, or it will go wrong.

This second parameter is an array of

If the second argument is an array, only the properties that appear in the array will be serialized into the result string, as long as the properties that are not found in the provided array are not included, and the attributes that exist in the source JS object are ignored, and no error is given.

1.3 The third parameter is used to beautify the output--not recommended

Specify the whitespace characters for indentation, and you can take the following values:

    • is a number of 1-10, representing a few white space characters
    • is a string, use the string instead of a space to take up to the first 10 characters of the string
    • Does not provide this parameter equals set to NULL equals set a number less than 1

Smile on the good, don't use, serialization is for transmission, transmission is the smaller the better, plus inexplicable indentation, parsing difficulties (if it is a string), but also weakened the characteristics of light weight.

1.4 Note the "cleverness" of this function (important)

If there are other uncertainties, then the best way is to "have a try" and the console does the experiment.

    • The key name is not double quotation marks (including no quotation marks or single quotation marks), will automatically become double quotation marks, the string is single quotation marks, will automatically become double quotation marks
    • The last property, followed by a comma, is automatically removed.
    • Properties of non-array objects cannot be guaranteed to appear in a serialized string in a particular order
    • This is a good understanding, that is, the non-array object in the final string does not guarantee the property order and the original consistency
    • The wrapped object of a Boolean, number, string is automatically converted to the corresponding original value during serialization
    • What is your new String ("Bala") becomes "Bala", and new number (2017) becomes 2017
    • Undefined, arbitrary functions (in fact, there is a function will happen magic, later said) and symbol value (symbol see ES6 for symbol)
      • Occurs in a property value of a non-array object: is ignored during serialization
      • When it appears in an array: is converted to null

    • NaN, Infinity, and-infinity, both in arrays and non-array objects, are converted to null
    • All attributes with the Symbol property key are completely ignored, even if the Replacer parameter is forced to specify that they are included
    • Non-enumerable properties are ignored

2.JSON string parsing to JS data structure

Parses a JSON string into a JS data structure--json.parse

The function signature for this function is this:

If the first argument, the JSON string, is not a valid string, then this function throws an error, so if you're writing a back-end script that returns a JSON string, it's best to call the language itself's JSON string-related serialization function.

In particular, if you are stitching the implemented serialized strings yourself, it is particularly important to note that the serialized string is legitimate and legally refers to the strict format in which the JSON string fully conforms to the JSON requirements.

It is important to note that there is an optional second parameter, which must be a function that will be processed and returned before the property has been parsed but not returned.

Take a closer look at these outputs, you can see that the traversal is from the inside out, probably from the inside out of the word will be misunderstood, the innermost is the inner array of two values ah, but the output is from the first property, how is it from the inside out?

This from the inside refers to the composite properties, in layman's terms, traverse the time, from beginning to end to traverse, if it is a simple attribute value (numeric, String, Boolean and null), then the direct traversal is completed.

If a property value is encountered as an object or an array, then pause to iterate through the JSON, and the principle of traversal is the same, and when this composite property traversal is completed, then the traversal of this property is returned.

Essentially, this is a depth-first traversal.

There are two points to note:

    • If Reviver returns undefined, the current property is removed from the owning object, and if other values are returned, the returned value becomes the new property value of the current property.
    • You can notice that the last set of outputs in the above example does not appear to have a key, in fact, this key is an empty string, and the last object is the last to parse the completed objects, because at the top, there is no real property.

3. Magical functions that affect json.stringify

The magical function of affecting json.stringify--object.tojson

If you implement the Tojson method on a JS object, then when calling Json.stringify to serialize the JS object, Json.stringify will serialize the value returned by the Tojson method of the object as a parameter.

That's the way this function is.

In fact, the date type can be passed directly to Json.stringify to do parameters, in which the reason is that the date type built-in Tojson method.

Summary and questions about compatibility

To here finally, JSON and JS in the JSON, comb the details and attention to the inside of a traversal, know that JSON is a syntax derived from the JS language of a Lightweight data interchange format, but also understand the JSON relative to the general JS data structure (especially the object) differences, Further, the 3 functions and details of the JSON processing in JS are discussed in detail.

Unfortunately, the 3 functions used above are incompatible with IE7 and the browser before IE7. For a discussion of compatibility, leave it to the next. If you want to solve the compatibility directly in the application, then you can apply the official JSON JS, can be resolved.

JSON initial knowledge

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.