如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 JSON基于JavaScript的语法,但完全独立于语言的文本格式,支持包括C, C++, C#, Java, JavaScript, Perl, Python等语言。
Object对象是一个无序
的键值对
(名称/值)的集合。
Object对象以{
左括号开始,以}
右括号结束。每个名称
后跟一个 :
冒号,键值对
之间使用,
逗号 分隔。
Array数组是值(value)
的有序
集合。数组以 [
左中括号 开始, ]
右中括号 结束。值
之间使用 ,
逗号 分隔。
值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array),并且这些结构可以嵌套。
字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。
数值(number)与C或者Java的数值非常相似。
这里以JavaScript为例。
{"firstName": "Zhang", "lastName": "San"}
{"name":[{"firstName":"Zhang","lastName":"San"},{"firstName":"Li","lastName":"Si"}]}
JSON对象转换为字符串
'use strict';
var json = JSON.stringify({a: 'Hello', b: 'World'});
console.log(typeof(json));// string
console.log(json); // '{"a": "Hello", "b": "World"}'
JSON字符串转换为对象
'use strict';
var obj = JSON.parse('{"a": "Hello", "b": "World"}');
console.log(typeof(obj));// object
console.log(obj); //{a: 'Hello', b: 'World'}
名称
取值
'use strict';
let obj = {a: "Hello", b: "World"};
console.log(obj.a); // Hello
console.log(obj['b']); // World
'use strict';
let obj = ["Hello", "World"];
console.log(obj[0]); // Hello
console.log(obj[1]); // World
键值对
'use strict';
let obj = {};
obj.a = "Hello";
obj["b"] = "World";
console.log(obj);// {a: "Hello", b: "World"}
名称
取值
'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
'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
该场景需要结合实际的业务
后续会比较一下二者的效率
例如,用户名与角色的对象关系
'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
为了进一步减少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更节约空间,并且一定程度上访问更便捷
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;
}
@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"
//}
'use strict'
let obj = { a: "Hello", b: "World" };
console.log(Object.keys(obj)); // Array(2) ["a", "b"]
'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"]]
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"}}
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"}]
https://github.com/zxlie/FeHelper
可以离线使用,支持JSON格式化,压缩及比对
其他略
cJSON
https://github.com/DaveGamble/cJSON
rapidjson
https://github.com/Tencent/rapidjson
https://github.com/alibaba/fastjson
https://github.com/google/gson
http://www.ecma-international.org/publications/standards/Ecma-262.htm
https://github.com/douglascrockford/JSON-js
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: