zoukankan      html  css  js  c++  java
  • JavaScript Patterns 3.5 JSON

    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.

    // 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" 

    using YUI3

    // 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"
    
    }); 

    using JQuery

    // an input JSON string
    
    var jstr = '{"mykey": "my value"}';
    
    var data = jQuery.parseJSON(jstr);
    
    console.log(data.mykey); // "my value" 

    JSON.stringify()

    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]}
  • 相关阅读:
    抛开BlazeDS,自定义flex RPC
    设计模式学习03装饰器模式
    通过ANT生成MANIFEST.MF中的ClassPath属性
    Spring JDBCTemplate与Hiberante混用
    关于 两个 datetime 列的差别导致了运行时溢出
    在Wcf中使用Nhibernate (续)
    sql2005/sql2008 分页
    工行支付api查询asp.net C# 实现
    生成静态页面的vbscript
    Asp.net Mvc Post ID Bug
  • 原文地址:https://www.cnblogs.com/haokaibo/p/JSON.html
Copyright © 2011-2022 走看看