ways to convert a string to a JSON object:
var str = ' {' name1 ': ' value1 ',' name2 ': ' value2'} ';(the conversion format of JSON must be a single quote set of double quotes)
1.json.parse (str);
2.eval ("(" +str+ ")");
3.var json = (new Function ("return" +str));
convert JSON into a string:
1.json.stringgify (JSON);
compatibility issues Json.parse () converts a string into a JSON object
IE7 and belowBrowser not supported (two other kinds of no problem)The following JS file can be introduced to solve this problem. Https://github.com/douglascrockford/JSON-js
Cast:
1 <!DOCTYPE HTML>2 <Htmllang= "en">3 <Head>4 <Metacharset= "UTF-8"/>5 <title>Document</title>6 </Head>7 <Body>8 </Body>9 <ScriptType= "Text/javascript">Ten //strings that do not conform to the JSON conversion format One varstring="{' age ': +, ' sex ': ' Boy '}"; A //Use the JSON cast method to convert the string (the new Function ("return" +str)); - varJSON=(Newfunction ("return"+string)) (); - Console.log (json.sex); the varLi=Document.createelement ("Li"); - Li.innertext="Name:"+Json.sex+", Age:"+Json.age; - Document.body.appendChild (LI); - </Script> + </HTML>
View Code
Effect:
ways to convert JSON data:JSON is the object, and the object is JSON;
1 <!DOCTYPE HTML>2 <Htmllang= "en">3 <Head>4 <Metacharset= "UTF-8"/>5 <title>Convert JSON data</title>6 </Head>7 <Body>8 </Body>9 <ScriptType= "Text/javascript"src= "Jquery-3.1.1.min.js"></Script>Ten <ScriptType= "Text/javascript"> One //also take advantage of casting A Data="{root:[{name: ' 1 ', Value: ' 0 '},{name: ' One ', Value: '},{name ': ' 1123 ', value: ' Guangdong '},{name: ' 1124 ', Value: ' Attachment '}]} "; - console.log (data); - varJSON=(Newfunction ("return"+data)) (); the Console.log (json.root); - $.each (Json.root,function(i,v) { - Console.log (v); - varh=v; + for(Keyinchh) { - Console.log (H[key]); + var$span= $("<span></span><br/>"); A $span. Text (H[key]); at $("Body"). Append ($span); - } - }); - </Script> - </HTML>
View Code
Effect:
Some ways to convert JSON and strings