js中json字符串与对象的转换及是否为空

时间:2023-01-30 06:55:28

1.json对象(数组)转字符串

var b=[ {
"CategoryName" : "Beverages",
"ProductName" : "Steeleye Stout",
"Country" : "UK",
"Price" : "1008.0000",
"Quantity" : "65"
}, {
"CategoryName" : "Beverages",
"ProductName" : "Laughing Lumberjack Lager",
"Country" : "USA",
"Price" : "140.0000",
"Quantity" : "10"
}];
console.log(JSON.stringify(b));

2.json字符串转对象
JSON.parse(jsonstr);

3.判断json是否为空

var a={aa:111,bb:222};

if(JSON.stringify(a) != "{}") 或者利用 Object.keys(a).length>0

json数组则jsArray.length>0;

4.存取值

var a={};

a.aa=111;

a["bb"]=222;

a["List"]=[{aa:111,bb:222},{aa:112,bb:223}];

a["List"][0].aa=113;

a["List"][0]["bb"]=224;

var b=[{aa:111,bb:222},{aa:112,bb:223}];

b[0].aa=114;

b[0]["bb"]=225;