On the syntax and format of JSON in JS _javascript tips

Source: Internet
Author: User
Tags eval

The JSON text format is syntactically the same as the code that creates the JavaScript object.

Because of this similarity, JavaScript programs can use the built-in eval () function to generate native JavaScript objects with JSON data without a parser.

JSON syntax rules:

Data in name/value pair
Data separated by commas
Curly Braces Save Objects
square brackets to save an array

JSON Name/value pair Introduction

"Name": "Zhang Fei",
"age": 23

The value of the JSON can be:

Number (integer or floating-point numbers)
String (to be included in double quotes)
Logical value (TRUE or FALSE)
Array (in square brackets)
Object (in curly braces)

The JSON-to-JavaScript object method is:

eval("(" + str + ")");

code example:

 

JSON and JavaScript Object conversions

 JSON goto JavaScript Object

JSON to Object 1
function Jsontoobject (str) {return
 eval ("+ str +"));
}

JSON-Object 2 
function Strtojson (str) {
 var json = (new function ("return" + str)) ();
 return JSON;
}

JSON to object 3 jquery tool function
$.parsejson ()

 JavaScript objects turn to JSON

JavaScript object turns JSON
function Objecttojson (o) {
 var arr = [];
 var FMT = function (s) {
  if (typeof s = = ' object ' && s!= null) return json2str (s);
  Return/^ (String|number) $/.test (typeof s)? "" + S + "'": S;
 }
 for (var i in O) arr.push ("' + i +" ': "+ FMT (O[i]));
 Return ' {' + arr.join (', ') + '} ';
}

The above is the entire content of this article, I hope to help you, thank you for the support of cloud habitat community!

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.