JavaScript JSON usage method

Source: Internet
Author: User
Tags data structures eval tojson

JSON is a subset of JavaScript object-oriented syntax. Because JSON is a subset of JavaScript, it can be used clearly in this language.

The text generates a JSON object that must be enclosed with a pair of parentheses.

Because JSON is a subset of the web effects, it's easy to use JSON in JavaScript.


JS Code

var myjsonobject = {"Bindings": [
{"Ircevent": "Privmsg", "Method": "Newuri", "regex": "^http://.*"},
{"Ircevent": "Privmsg", "Method": "Deleteuri", "regex": "^delete.*"},
{"Ircevent": "Privmsg", "Method": "Randomuri", "regex": "^random.*"}
]
};

In the example above, we created an object that contains only one member "bindings", and bindings contains an array of 3 objects. These 3 objects all contain 3 members: "Ircevent", "Method", "regex".

In JavaScript, members can be obtained by using the dot number.
Like what:

JS Code

Myjsonobject.bindings[0].method

The eval () function enables you to convert a JSON string to an object.

JS Code

var myObject = eval (' (' + myjsontext + ') ');

The Eval function is very fast, but it can compile any javascirpt code, which could create a security problem. The use of Eval is based on the assumption that the code parameters passed in are reliable, and in some cases the client may be untrusted.

If you are considering security considerations, it is a good idea to use a JSON parser. A JSON parser will only accept JSON text. So it's more secure.

JS Code

var myObject = Json.parse (myjsontext, filter);

The optional filter parameter traverses each value key pair and carries out related processing. Such as:


JS Code

MyData = json.parse (text, function (key, value) {

return Key.indexof (' date ') >= 0?    New Date (value): value; });

The Stringifier function is the opposite of parse, used to convert a JS object to JSON text.

JS Code
var myjsontext = Json.stringifier (MyObject);


var myjsonobject = {"Bindings": [
{"Ircevent": "Privmsg", "Method": "Newuri", "regex": "^http://.*"},
{"Ircevent": "Privmsg", "Method": "Deleteuri", "regex": "^delete.*"},
{"Ircevent": "Privmsg", "Method": "Randomuri", "regex": "^random.*"}
]
};

The above example creates an object that includes a separate member, "bindings," that includes an array of three objects ("Ircevent", "Method", and "regex")

Members can be retrieved by the. or subscript operator.

Myjsonobject.bindings[0].method//"Newuri"

To convert JSON text to objects, you can use the eval () function. The eval () function calls the JavaScript editor. Because JSON is a subset of JavaScript, the compiler will parse the text correctly and produce an object structure. Text must be enclosed in parentheses to avoid grammatical ambiguity in JavaScript.

var myObject = eval (' (' + myjsontext + ') ');

The Eval function is very fast. It can compile and execute any JavaScript program, thus creating a security issue. You can use the Eval function when you are using trusted and sophisticated source code. This makes it more secure to use the JSON parser. With XMLHttpRequest Web applications, communication between pages only allows homology and therefore can be trusted. But this is not perfect. If the server does not have a rigorous JSON encoding, or if there is no strict input validation, then it is possible to route invalid JSON literals that include dangerous scripts. The Eval function will execute a malicious script.

Use the JSON parser to prevent such events. The JSON parser can only recognize JSON text and reject all scripts. The JSON parser for browsers that provide local JSON support will be much faster than the Eval function. The future ECMAScript standard is expected to support local JSON.

var myObject = Json.parse (Myjsontext, reviver);

A substitution function (Reviver function) is invoked as an optional parameter by the key (key) and value (value) of the final result. Each value is replaced by the value of the substituted function. This can be used to change a generic class to an instance of a pseudo class, or to convert a date string to a Date object.

MyData = json.parse (text, function (key, value) {
var type;
if (value && typeof value = = = ' object ') {
Type = Value.Type;
if (typeof type = = ' string ' && typeof window[type] = = = ' function ') {
return new (Window[type]) (value);
}
}
return value;
});

The JSON stringifier is reversed to convert the JavaScript data structure to JSON text. JSON does not support looping data structures, so be careful not to provide a looping structure for JSON stringifier.

var myjsontext = json.stringify (MyObject, replacer);

If the Stringify function finds an object with a Tojson method, it executes this method and returns the resulting value. Such an object can determine its own JSON performance.

The Stringifier method can carry an optional array of strings. These strings are used to select the attributes that are included in the JSON text.

The Stringifier method can carry an optional substitution (replacer) function. It will be executed after the Tojson method (if any) for each value in the structure. It passes each key and value as a parameter, and of course the object contains the key. The return value will be serialized.

If an array or substitution function is not provided, an optional substitution function for ignoring the integrated attribute will be provided. If you want all inherited properties, you can provide a simple substitution function:

var myjsontext = json.stringify (myObject, function (key, value) {
return value;
});

The values that are not expressed in JSON, such as functions and undefined, are excluded.

The quantity that is not determined will be replaced with NULL. To replace other values, you can use the substitution (replacer) function as follows

function Replacer (key, value) {
if (typeof value = = = ' Number ' &&!isfinite (value)) {
return String (value);
}
return value;
}

This is a foreign website

The JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript and it can be used in the language with no muss or fuss.

var myjsonobject = {"Bindings": [
{"Ircevent": "Privmsg", "Method": "Newuri", "regex": "^http://.*"},
{"Ircevent": "Privmsg", "Method": "Deleteuri", "regex": "^delete.*"},
{"Ircevent": "Privmsg", "Method": "Randomuri", "regex": "^random.*"}
]
};

In this example, an object is created containing a single "bindings", which contains an array containing three CTS, each containing ' ircevent ', ' method ', and ' regex ' members.

Members can be retrieved using dot or subscript operators.

myjsonobject.bindings[0].method   //"Newuri"
to convert a JSON text in an object, and can use th e eval () function. Eval () invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler would correctly parse the text and produce an object structure. The text must is wrapped in parens to avoid tripping on a ambiguity in JavaScript ' s syntax.

var myObject = eval (' + Myjsontext + '); The
the Eval function is very fast. However, it can compile and execute any JavaScript program, so there can is security issues. The use of the ' eval is ' indicated when the ' source is trusted and competent. It is very safer to use a JSON parser. In Web applications over XMLHttpRequest, communication are permitted only to the same origin that provide that page and so it is trusted. But it might not is competent. If The server is isn't rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it cou LD deliver invalid JSON text that could is carrying dangerous script. The Eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser'll recognize only JSON-text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are a much also faster eval. It is expected that native JSON support would be included in the next ECMAScript standard.

var myObject = Json.parse (Myjsontext, reviver);

The optional reviver parameter is a function that'll be called for every key and value at every level of the final Resul T. Each value is replaced by the result of the Reviver function. This can is used to reform generic objects into instances of PS Tutorial eudoclasses, or to transform date strings into date objec Rsh

MyData = json.parse (text, function (key, value) {
var type;
if (value && typeof value = = = ' object ') {
Type = Value.Type;
if (typeof type = = ' string ' && typeof window[type] = = = ' function ') {
return new (Window[type]) (value);
}
}
return value;
});

A json Stringifier goes in the opposite direction, converting JAVASCRIPT data structures into JSON text. JSON does not support cyclic data structures, so is careful to not give cyclical to the JSON structures.

var myjsontext = json.stringify (MyObject, replacer);

If The Stringify method is sees an object to contains a Tojson method, it calls this method, and stringifies the value Retu rned. This is allows an object to determine its own JSON representation.

The Stringifier method can take an optional array of strings. These strings are used to select the properties that would be included in the JSON text.

The Stringifier method can take a optional replacer function. It'll be called after the Tojson method (if there are one) on each of the values in the structure. It'll be passed each key and value as parameters, and this would be bound to object holding the key. The value returned would be stringified.

Values that does not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function Replacer (key, value) {
if (typeof value = = = ' Number ' &&!isfinite (value)) {
return String (value);
}
return value;
}

Giving a corresponding reviver to Json.parse can undo that.

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.