JS/Jquery遍历JSON对象、JSON数组、JSON数组字符串、JSON对象字符串

时间:2024-01-05 17:30:08

JS遍历JSON对象

JS遍历JSON对象

<script>
var obj = {
"goodsid": "01001", "goodsname": "铅笔", "goodsprice": "1.5"
};
</script>

JS遍历方法

  for (var key in obj) {
document.write(obj[key]+"<br>");
}

Jquery遍历方法

        $.each(obj, function (index, value) {
alert(value);
});
</script>

JS遍历JSON数组

JSON数组

var jsonArr = [

            {

                "goodsid": "01001",
"goodsname": "铅笔",
"goodsprice": "1.5" }, { "goodsid": "01002",
"goodsname": "钢笔",
"goodsprice": "25" }, { "goodsid": "01003",
"goodsname": "毛笔",
"goodsprice": "15" } ];

JS遍历方法

for (var i = 0, l = jsonArr.length; i < l; i++) {
for (var key in jsonArr[i]) {
document.write(key + ':' + jsonArr[i][key]+"<br>");
}
}

JQ遍历方式

$.each(jsonArr,function(index,value){
alert(value.year);
});

遍历JSON对象字符串

1JSON字符串

 var str = {
"goodsid": "01001", "goodsname": "铅笔", "goodsprice": "1.5"
};

遍历方式:先将字符串转换为JSON对象

var obj = JSON.parse(str);

再用遍历JSON对象的方式遍历它,方式与前面一样,不再表述。

遍历JSON数组字符串

JSON数组字符串

var jsonArrStr= [

            {

                "goodsid": "01001",
"goodsname": "铅笔",
"goodsprice": "1.5" }, { "goodsid": "01002",
"goodsname": "钢笔",
"goodsprice": "25" }, { "goodsid": "01003",
"goodsname": "毛笔",
"goodsprice": "15" } ];

遍历方式:先将字符串转换为JSON数组

var jsonArr = $.parseJSON(jsonArrStr);

再用遍历JSON数组的方式遍历它,方式与前面一样,不再表述。