首页 > 编程语言 > 详细

JavaScript Patterns 3.5 JSON

时间:2014-06-02 09:30:09      阅读:354      评论:0      收藏:0      [点我收藏+]

JSON: JavaScript Object Notation

{"name": "value", "some": [1, 2, 3]} 

The only syntax difference between JSON and the object literal is that property names need to be wrapped in quotes to be valid JSON. In object literals the quotes are required only when the property names are not valid identifiers, for example, they have spaces {"first name": "Dave"}.

In JSON strings you cannot use functions or regular expression literals. 

Working with JSON

JSON.parse()

use the JSON.parse()method, which is part of the language since ES5 and is natively provided by the JavaScript engines in modern browsers.

For older JavaScript engines, you can use the JSON.org library (http://www.json.org/json2.js) to gain access to the  JSON object and its methods.

bubuko.com,布布扣
// an input JSON string

var jstr = ‘{"mykey": "my value"}‘; 

// antipattern

var data = eval(‘(‘ + jstr + ‘)‘); 

// preferred

var data = JSON.parse(jstr);

console.log(data.mykey); // "my value" 
bubuko.com,布布扣

using YUI3

bubuko.com,布布扣
// an input JSON string

var jstr = ‘{"mykey": "my value"}‘; 

// parse the string and turn it into an object

// using a YUI instance

YUI().use(‘json-parse‘, function (Y) {

    var data = Y.JSON.parse(jstr);

    console.log(data.mykey); // "my value"

}); 
bubuko.com,布布扣

using JQuery

bubuko.com,布布扣
// an input JSON string

var jstr = ‘{"mykey": "my value"}‘;

var data = jQuery.parseJSON(jstr);

console.log(data.mykey); // "my value" 
bubuko.com,布布扣

JSON.stringify()

bubuko.com,布布扣
var dog = {

    name: "Fido",

    dob: new Date(),

    legs: [1, 2, 3, 4]

};

var jsonstr = JSON.stringify(dog);

// jsonstr is now:

// {"name":"Fido","dob":"2010-04-11T22:36:22.436Z","legs":[1,2,3,4]}
bubuko.com,布布扣

JavaScript Patterns 3.5 JSON,布布扣,bubuko.com

JavaScript Patterns 3.5 JSON

原文:http://www.cnblogs.com/haokaibo/p/JSON.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!