今天用到了json数组和json对象和json类型字符串之间互转及取值,记录一下:

1.json类型的字符串转换为json对象及取值

  var jsonString = '{"bar":"property","baz":3}';
var jsObject = JSON.parse(jsonString); //转换为json对象
alert(jsObject.bar); //取json中的值

2.json对象转为json类型的字符串

var jsonString = '{"bar":"property","baz":3}';

var jsObject = JSON.parse(jsonString); //转换为json对象

alert(jsObject.bar); //取json中的值

var st = JSON.stringify(jsObject); //转换为json类型的字符串  

3.json数组类型的字符串转换为json及取值 和json对象转换为转换为json字符串

 //json数组类型字符串取值
var jsonStr = '[{"id":"01","open":false,"pId":"0","name":"A部门"},{"id":"01","open":false,"pId":"0","name":"A部门"},{"id":"011","open":false,"pId":"01","name":"A部门"},{"id":"03","open":false,"pId":"0","name":"A部门"},{"id":"04","open":false,"pId":"0","name":"A部门"}, {"id":"05","open":false,"pId":"0","name":"A部门"}, {"id":"06","open":false,"pId":"0","name":"A部门"}]';
var jsonObj = JSON.parse(jsonStr);//转换为json对象
for(var i=0;i<jsonObj.length;i++){
alert(jsonObj[i].id); //取json中的值
}
console.log(jsonObj)
var jsonStr1 = JSON.stringify(jsonObj)
console.log(jsonStr1+"jsonStr1")

结果:

javascript中json对象json数组json字符串互转及取值-LMLPHP

04-26 09:57