JSON数组转换为Javascript数组

时间:2012-03-06 10:16:06

标签: javascript json

您好。我在JSON中得到了输出...现在我需要将这些数据转换为javascript ..

如何在javascript中编写代码? 我必须将图像显示到浏览器..只有通过在javascript中编写代码才有可能。 救救我..

我的JSON输出是..

    [{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},
     {"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},
     {"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]

5 个答案:

答案 0 :(得分:34)

  

hai我的输出是 JSON ...现在我需要将这些数据转换成   的JavaScript ..

使用JSON.parse()函数将其转换为JS对象。

var obj = JSON.parse(yourJsonString);

现在您可以使用for-in循环迭代其每个项目:

for (var x in obj){
  if (obj.hasOwnProperty(x)){
    // your code
  }
}

答案 1 :(得分:2)

你应该可以将它用作一个对象,它支持数组的所有关键功能

答案 2 :(得分:2)

如果您使用的是jQuery,可以使用

var object = $.parseJSON(jsonstring);

或者添加此库https://raw.github.com/douglascrockford/JSON-js/master/json2.js并提供

var object = JSON.parse(jsonstring);

答案 3 :(得分:1)

正如萨夫拉兹所说,

var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
// obj now contains the array!

编辑:用于显示图像:

for (var i = 0, len = obj.length; i < len; i++){
    var img = new Image();
    img.setAttribute("src",obj[i][2] + obj[i][1]);
    document.body.appendChild(img);
}

答案 4 :(得分:0)

这是我的两分钱:

var my_json = [{created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"},{created_at: "2019-03-14T01:00:32Z", entry_id: 33359, field1: "4", field2: "4", field3: "0"}];

var data =[];
var dataSet=[];
	my_json.forEach((val,index)=>{
		if(my_json[index]!==null){
			for(var i in my_json[index]) {
					data.push(my_json[index][i]);
			}
			dataSet.push(data);
			data=[];
		}	
	})
console.log("...java Script Array... \n"+JSON.stringify(dataSet));