[2017-03-09]深入浅出理解JSON

来源:互联网 发布:php mysqli连接数据库 编辑:程序博客网 时间:2024/06/03 12:40

一、开篇之言

关于JSON,最重要的是要理解它是一种数据格式,不是一种编程语言。虽然具有相同的语法形式,但是JSON并不从属于Javascript。而且很多编程语言都有针对于JSON的解析器和序列化器。

【一幅图帮助你理解JSON】



二、JSON语法

1. 简单值

example:5  , "Hello World!"

JSON与Javascript的最大区别在于JSON的字符串必须加双引号,而js既可以加双引号" "也可以加单引号' '

2. 对象

JSON对象与js字面量稍微有一些不同

example:

- [javascript中的字面量对象] 

var book = {     title:  "深入浅出JSON",     author: "Helen",     time: "2017-03-09"     };

- [JSON表示上述对象] 

{     "title":  "深入浅出JSON",     "author": "Helen",     "time": "2017-03-09"     }
总结一下:
   (1)JSON中没有申明变量
(2)对象属性加双引号,末尾没有分号

3. 数组
- [javascript中的字面量对象] 
var values = ["ab", "cd", "ef"];

- [JSON表示上述对象] 
["ab", "cd", "ef"]
同对象一样,JSON数组没有变量和分号


三、解析与序列化

JSON对象有两个方法,分别为JSON.stringify()和JSON.parse() 方法。

其中,JSON.stringify()是将javascript对象序列化为JSON字符串,JSON.parse()是把JSON字符串解析为javascript值

1. JSON.stringify()

方法有三个参数,分别为JSON.stringify(需要序列化的对象, "过滤器(数组/函数), "缩进长度/缩进符号")

2. JSON,parse()

该方法函数也称为还原函数,如果还原函数返回undefined,则表示要从结果中删除相应的键


【下面为解析和序列化的一个demo,环境为node.js】

var book = {    "title": "Professional JavaScript",    "author": ["Nicholas C.Zakas"],    "edition":3,    "year": 2011,    // toJSON: function(){    //     return this.title;    // }};//use the method of JSON.stringify() var jsonText = JSON.stringify(book,["title", "edition"]);console.log("=======序列化为JSON=======");console.log(jsonText +'\n');//use the method of JSON.parsevar bookCopy =  JSON.parse(jsonText);console.log("=======解析为javascript值=======");console.log(bookCopy);console.log("\n");//the second parameter of JSON.stringify() is a functionvar jsonText_function = JSON.stringify(book, function(key,value){    switch(key){        case "author":            return value.join(",")        case "year":            return 5000;        case "edition":            return undefined;        default:            return value;    }});console.log("=======JSON.stringify()第二个参数为函数=======");console.log(jsonText_function +'\n');//the use of the third parameter of JSON.stringify() is indenting//var jsonText_indent = JSON.stringify(book, null, "--")var jsonText_indent = JSON.stringify(book, null, 4);console.log("========控制字符串缩进========");console.log(jsonText_indent +'\n');/** * //the method of toJSON* var toJsonText = JSON.stringify(book);* console.log("========toJSON()方法========");* console.log(toJsonText);**/ 

0 0