JSON字符串: var str1 = '{ "name": "cxh", "sex": "man" }'; JSON对象: var str2 = { "name": "cxh", "sex": "man" };
1.字符串转JSON
var obj = JSON.parse(str1);
2.JSON转字符串
var str=JSON.stringify(obj);
3.JSON增加元素
obj['key']=value;或者obj.key=value;
4.JSON删除元素
delete obj["key"];
5.JSON按数字排序
obj.sort(sortBy('key', false, parseInt));
6.JSON按字符串排序
obj.sort(sortBy('key', false, String));
7.得到某个属性的值
obj.key或者obj['key']
注释:
-
中括号运算符总是能代替点运算符。但点运算符却不一定能全部代替中括号运算符。
-
中括号运算符可以用字符串变量的内容作为属性名。点运算符不能。
-
中括号运算符可以用纯数字为属性名。点运算符不能。
-
中括号运算符可以用js的关键字和保留字作为属性名。点运算符不能。
ps:点号后加标识符(静态的)
中括号放字符串,字符串可以是动态的,obj['string'+variable]
如果是静态的还是用点号方便