Reputation: 977
Hi. I got my output in JSON... Now I need to convert those data into javascript..
How to write the code in javascript? I have to display the images to the browser.. it is possible only by writing the code in javascript. Help me..
My JSON output is..
[{"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\/"}]
Upvotes: 26
Views: 88272
Reputation: 3949
Here are my two cents :
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));
Upvotes: -1
Reputation: 25135
If you are using jQuery you can use
var object = $.parseJSON(jsonstring);
Or add this library https://raw.github.com/douglascrockford/JSON-js/master/json2.js and give
var object = JSON.parse(jsonstring);
Upvotes: 4
Reputation: 1306
As Sarfraz is saying,
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!
EDIT: For it to display the images:
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);
}
Upvotes: 1
Reputation: 382606
hai i got my output in JSON...now i need to convert those data into javascript..
Use JSON.parse()
function in order to convert it to JS object.
var obj = JSON.parse(yourJsonString);
And now you can use for-in
loop to iterate over each of its items:
for (var x in obj){
if (obj.hasOwnProperty(x)){
// your code
}
}
Upvotes: 45
Reputation: 30651
you should be able to use it as an object, which supports all of the key functions of an array
Upvotes: 2