How string format JSON is translated into JSON object in JavaScript

Source: Internet
Author: User
Tags tojson

What is JSON

JSON (JavaScript Object Notation) is a graceful way to create JavaScript objects. JSON is also a lightweight data interchange format. JSON is very easy for people to read and write, while facilitating machine parsing and generation. JSON is a better solution for exchanging data in Ajax instead of XML.

JSON format and syntax

var jsonobject=
{
property syntax within an object (property names and property values are paired)
Propertyname:value,

function syntax within an object (the function name is paired with its contents)
Functionname:function () {...;}
};

Jsonobject--JSON object name
PropertyName--Property name
FunctionName--Function name
A pair of curly braces that enclose multiple "name/value" collections
JSON is represented by a collection of name/value pairs, or it can be understood as an array
The property name or function name can be any string, even an empty string (see example below)
Commas are used to separate each pair of "name/value" pairs

There are 3 ways to convert a string format JSON into a JSON object:
1:js using eval to generate JSON objects---Use the eval () function to convert a JSON string into an object.
2: Use function mode
3: Use JS JSON library or jquery to provide the JS library---if security-based considerations, it is best to use a JSON parser. A JSON parser will only accept JSON text. So it's more secure.

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >//method 1:js using eval to generate a JSON object            functionStrjsontojsonbyeval (jsondata) {varJSON = eval ("(" + Jsondata + ")");//convert to JSON object                returnJSON; }                        //Method 2: Use function mode            functionstrjsontojsonbyfunction (jsondata) {return(NewFunction ("return" +jsondata))             (); } window.onload=function() {                varJsondata = "{name1: ' 1 ', value1: ' A ', name2: ' 2 ', value2: ' B '}"; varJson1 =strjsontojsonbyfunction (Jsondata); Alert ("Function | |" + JSON1.NAME1 + "---" +json1.name2); varJson2 = eval ("({name1: ' 1 ', value1: ' A ', name2: ' 2 ', value2: ' B '})"); Alert ("Eval (\" (\ "jsondata\") \ ") | | "+ json2.value1 +"---"+json2.value2); varJson3 =Strjsontojsonbyeval (Jsondata); Alert ("Eval | |" + json3.value1 + "---" +json3.value2); }        </script> 

Write a method:

/** @method convert JSON into JSON object with good string format * @param jsondata param fomart: * var jsondata             = "{name1: ' 1 ', value1: ' A ', name2: ' 2 ', value2: ' B '}";             * @return JSON; */            functionStrjsontojson (jsondata) {//method 1:js using eval to generate a JSON object                //var json = eval ("(" + Jsondata + ")");//Convert to JSON object                //return JSON;                //Method 2: Use function mode                return(NewFunction ("return" +jsondata))             (); }

Jquery

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">/*Jquery-1.9.1.js provides the method. Jquery.parsejson (JSON) returns: Object accepts a JSON string in a standard format and returns the parsed JavaScript object. Passing in a malformed JSON string can cause an exception to be thrown. For example, the following JSON string formats are not correct: {test:1} (test does not use double-quote wrapping). {' Test ': 1} (' Test ' is wrapped in single quotation marks instead of double quotes). In addition, if you pass in nothing, or pass in an empty string, null, undefined, and so on, Parsejson will return null. If the browser natively implements Json.parse, JQuery uses it to parse the string. */varStrjson = ' {' name ': ' John '} ';//var Strjson = "{name: ' John '}";//error format, must strictly satisfy a standard format JSON string, Key--value are wrapped in double quotesvarobj =Jquery.parsejson (Strjson); alert (Obj.name= = = "John");//truevarObj2 =$.parsejson (Strjson); alert (obj2.name);//John/*Jquery.json-2.4.js provides the method. The following method is not very strict in accepting a standard format JSON string, as long as it is a key-value pair form. Http://code.google.com/p/jquery-json/toJSON:Serializes a JavaScript object, number, string, or array into Json.evaljson : Converts from JSON to Javascript, quickly, and is trivial.*///Json ObjectvarJSON = {plugin: ' Jquery-json ', version:2.4 };//Tojson:json Object---> String Jsonvarencoded = $.tojson (JSON);//' {' plugin ': ' Jquery-json ', ' Version ': 2.4} ' //evaljson:string JSON---> JSON ObjectvarJsonobject =$.evaljson (encoded);varName = $.evaljson (encoded). Plugin;//"Jquery-json"varVersion = $.evaljson (encoded). version;//2.4Alert ("ToJSON:" + encoded + ", typeof" +typeofEncoded + "\r\n\r\n" + "Evaljson:" + Jsonobject + ", typeof" +typeof(jsonobject) + "\r\n\r\n" + "name=" + name + ", version=" +version);</script>

http://rogerfederer.iteye.com/blog/1798024

How string format JSON is translated into JSON object in JavaScript

Related Article

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.