深入浅出JSON

深入浅出JSON


如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033

文章目录

  • 深入浅出JSON
    • @[toc]
    • 1. JSON简介
    • 2.JSON语法
      • 2.1 Object对象
      • 2.2 Array数组
      • 2.3 value值
      • 2.4 string字符串
      • 2.5 number数值
    • 3.JSON基本用法
      • 3.1 Object对象示例
      • 3.2 Array数组示例
      • 3.3 JSON序列化与反序列化
      • 3.3.1 序列化
        • 3.3.2 反序列化
      • 3.4 Object对象已知`名称`取`值`
      • 3.5 Array数组取值
    • 4.JSON进阶用法
      • 4.1 动态增加`键值对`
      • 4.2 未知`名称`取`值`
        • 4.2.1 Object对象
        • 4.2.2 Array数组
      • 4.3 JSON存储结果的适度优化
      • 4.4 Array数组的存储优化
      • 4.4 JSON.stringify参数控制
      • 4.4 json获取所有key
      • 4.5 json数组根据某个字段的值排序
      • 4.6 json数组转为map
      • 4.7 删除json元素
    • 5.JSON工具
      • 5.1 Chrome插件FeHelper
      • 5.2 略
    • 6.类库
      • 6.1 C
      • 6.2 C++
      • 6.3 Java
      • 6.4 JavaScript
      • 6.5 Lua

1. JSON简介

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 JSON基于JavaScript的语法,但完全独立于语言的文本格式,支持包括C, C++, C#, Java, JavaScript, Perl, Python等语言。

2.JSON语法

2.1 Object对象

Object对象是一个无序键值对(名称/值)的集合。

Object对象以{左括号开始,以}右括号结束。每个名称后跟一个 :冒号,键值对之间使用,逗号 分隔。

深入浅出JSON_第1张图片

2.2 Array数组

Array数组是值(value)有序集合。数组以 [左中括号 开始, ]右中括号 结束。之间使用 ,逗号 分隔。

深入浅出JSON_第2张图片

2.3 value值

值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array),并且这些结构可以嵌套。

深入浅出JSON_第3张图片

2.4 string字符串

字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。

深入浅出JSON_第4张图片

2.5 number数值

数值(number)与C或者Java的数值非常相似。

3.JSON基本用法

这里以JavaScript为例。

3.1 Object对象示例

{"firstName": "Zhang", "lastName": "San"}

3.2 Array数组示例

{"name":[{"firstName":"Zhang","lastName":"San"},{"firstName":"Li","lastName":"Si"}]}

3.3 JSON序列化与反序列化

3.3.1 序列化

JSON对象转换为字符串

'use strict';

var json = JSON.stringify({a: 'Hello', b: 'World'});
console.log(typeof(json));// string
console.log(json); // '{"a": "Hello", "b": "World"}'

3.3.2 反序列化

JSON字符串转换为对象

'use strict';

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
console.log(typeof(obj));// object
console.log(obj); //{a: 'Hello', b: 'World'}

3.4 Object对象已知名称

'use strict';

let obj = {a: "Hello", b: "World"};
console.log(obj.a); // Hello
console.log(obj['b']); // World

3.5 Array数组取值

'use strict';

let obj = ["Hello", "World"];
console.log(obj[0]); // Hello
console.log(obj[1]); // World

4.JSON进阶用法

4.1 动态增加键值对

'use strict';

let obj = {};
obj.a = "Hello";
obj["b"] = "World";
console.log(obj);// {a: "Hello", b: "World"}

4.2 未知名称

4.2.1 Object对象

'use strict';

let obj = { a: "Hello", b: "World" };

for (var key in obj) {
    let value = obj[key];//通过key取值
    console.log("key : " + key + ", value : " + value); // key : a, value : Hello
}

结果:

key : a, value : Hello
key : b, value : World

4.2.2 Array数组

'use strict';

let obj = ["Hello", "World"];

for (var key in obj) {
    let value = obj[key];//通过key取值
    console.log("key : " + key + ", value : " + value);
}

结果:

key : 0, value : Hello
key : 1, value : World

4.3 JSON存储结果的适度优化

该场景需要结合实际的业务

后续会比较一下二者的效率

例如,用户名与角色的对象关系

'use strict';

let obj1 = { "user": [{ "name": "ZhangSan", "age": "30", "role": "admin" }, { "name": "LiSi", "age": "29", "role": "None" }] };

// 以空间换时间
let obj2 = { "user": { "ZhangSan": { "name": "ZhangSan", "age": "30", "role": "admin" }, "LiSi": { "name": "LiSi", "age": "29", "role": "None" } }, "role": { "admin": ["ZhangSan"], "None": ["LiSi"] } };

// 1.查找ZhangSan的角色
let userObj = obj1['user']
for (let key in userObj) {
    if (userObj[key]['name'] === 'ZhangSan') {
        console.log("obj1 : " + userObj[key]['role']);// obj1 : admin
    }
}

console.log("obj2 : " + obj2['user']['ZhangSan']['role']);// obj2 : admin


// 2.查找角色为admin的用户
let roleUserList = []
for (let key in userObj) {
    if (userObj[key]['role'] === 'admin') {
        roleUserList.push(userObj[key]['name']);
    }
}

console.log("obj1 : " + roleUserList);// obj1 : ZhangSan

console.log("obj2 : " + obj2['role']['admin']);// obj2 : ZhangSan

4.4 Array数组的存储优化

为了进一步减少JSON的大小,对于Array数组可以做一定的优化。

示例如下:

'use strict';

let obj = {"students":[{"name":"ZhangSan","age":18},{"name":"LiSi","age":17},{"name":"WangWu","age":19}]};

let obj2 = {"studentInfo":{"name":0,"age":1},"Values":[["ZhangSan",18],["LiSi",17],["WangWu",19]]};

console.log(obj['students'][0]['name']);// ZhangSan

console.log(obj2['Values'][0][obj2['studentInfo']['name']]);// ZhangSan
console.log(obj2['Values'][0][0]);// ZhangSan
console.log(obj2['Values'][1][0]);// LiSi

对于obj2可以达到和obj同样的目的,obj2更节约空间,并且一定程度上访问更便捷

4.4 JSON.stringify参数控制

  • JSON.stringify函数释义
interface JSON {
    /**
      * Converts a JavaScript Object Notation (JSON) string into an object.
      * @param text A valid JSON string.
      * @param reviver A function that transforms the results. This function is called for each member of the object.
      * If a member contains nested objects, the nested objects are transformed before the parent object is.
      */
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
    /**
      * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
      * @param value A JavaScript value, usually an object or array, to be converted.
      * @param replacer A function that transforms the results.
      * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
      */
    stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
    /**
      * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
      * @param value A JavaScript value, usually an object or array, to be converted.
      * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
      * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
      */
    stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}
  • JSON.stringify参数解释

@param value 待转换的Object对象或Array数组

@param replacer 需要被序列化的字符串或数值的数组

@param space 增加缩进,空格和换行符到返回值JSON文本中,使其更易于阅读

  • 代码
'use strict';

let obj = { a: "Hello", b: "World" };

let result1 = JSON.stringify(obj, ['a']);
console.log(result1); // {"a":"Hello"}

let result2 = JSON.stringify(obj, ['b'], ' ');
console.log(result2); 
//{
// "b": "World"
//}

4.4 json获取所有key

'use strict'

let obj = { a: "Hello", b: "World" };

console.log(Object.keys(obj)); // Array(2) ["a", "b"] 

4.5 json数组根据某个字段的值排序

'use strict'

var data1 = [{
    name: "a",
    value: 1
}, {
    name: "b",
    value: 3
}, {
    name: "c",
    value: 2
}];

var data2 = [
    ["a", "1"],
    ["b", "3"],
    ["c", "2"]
]

//定义一个比较器--升序排列
function compare(propertyName) {
    return function (obj1, obj2) {
        var v1 = obj1[propertyName];
        var v2 = obj2[propertyName];
        if (v2 < v1) {
            return 1;
        } else if (v2 > v1) {
            return -1;
        } else {
            return 0;
        }
    }
}
console.info(JSON.stringify(data1)); // [{"name":"a","value":1},{"name":"b","value":3},{"name":"c","value":2}]
data1.sort(compare("value"));
console.info(JSON.stringify(data1)); // [{"name":"a","value":1},{"name":"c","value":2},{"name":"b","value":3}]

console.info(JSON.stringify(data2)); // [["a","1"],["b","3"],["c","2"]]
data2.sort(compare(1));
console.info(JSON.stringify(data2)); // [["a","1"],["c","2"],["b","3"]]

4.6 json数组转为map

json数组节约空间便于存储,但是不便于检索。可以将json数组转换为特定的map进行检索。可参考4.3节

'use strict'

let obj1 = [{ "name": "ZhangSan", "age": "30", "role": "admin" }, { "name": "LiSi", "age": "29", "role": "None" }];

let obj2 = {}
// 对数组进行map转换
for (const key in obj1) {
    obj2[obj1[key].name] = obj1[key];
}

console.log(JSON.stringify(obj2)); // {"ZhangSan":{"name":"ZhangSan","age":"30","role":"admin"},"LiSi":{"name":"LiSi","age":"29","role":"None"}}

4.7 删除json元素

delete object.property

object 对象的名称,或计算结果为对象的表达式。
property 要删除的属性。

'use strict'

let obj = [{ "name": "ZhangSan", "age": "30", "role": "admin" }, { "name": "LiSi", "age": "29", "role": "None" }];

console.log(JSON.stringify(obj)); // [{"name":"ZhangSan","age":"30","role":"admin"},{"name":"LiSi","age":"29","role":"None"}]

delete obj[0].age;

console.log(JSON.stringify(obj)); // [{"name":"ZhangSan","role":"admin"},{"name":"LiSi","age":"29","role":"None"}]

5.JSON工具

5.1 Chrome插件FeHelper

https://github.com/zxlie/FeHelper

可以离线使用,支持JSON格式化,压缩及比对

5.2 略

其他略

6.类库

6.1 C

cJSON

https://github.com/DaveGamble/cJSON

6.2 C++

rapidjson

https://github.com/Tencent/rapidjson

6.3 Java

  • fastjson

https://github.com/alibaba/fastjson

  • gson

https://github.com/google/gson

6.4 JavaScript

  • JSON

http://www.ecma-international.org/publications/standards/Ecma-262.htm

  • json2.js

https://github.com/douglascrockford/JSON-js

6.5 Lua

JSON Modules

http://lua-users.org/wiki/JsonModules


觉得文章对你有帮助,可以扫描二维码捐赠给博主,谢谢!
在这里插入图片描述
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033


License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎


Reference:

  1. http://www.json.org/

你可能感兴趣的:(JSON,json,序列化,json优化,json动态增加数据,json未知key取值)