I want to transform a JSON object into an array.
Am using a PHP script to create a JSON file using this code:
$stores = array();
$i=0;
$reponse = $bdd->query('select * from store ');
while ($donnees = $reponse->fetch())
{
$stores[$i] = $donnees;
$i++;
}
var_dump($stores);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($stores));
fclose($fp);
In my JS file am using this code to load the data:
var json_obj = $.getJSON("results.json", function (data) {
json_obj = data;
return json_obj;
});
alert(JSON.stringify(json_obj));
Now I want to transform my JSON object into a JavaScript array. But in specific way:
var props=[] ;
props.push({title:json_obj[0].name,Data:json_obj[0].Description});
props.push({title:json_obj[1].name,Data:json_obj[1].Description});
$.each(props, function (i,v)
{
console.log(i,v);
});
-
Arrays in javascript MUST have numeric index, start at 0 and have no gaps.Honk der Hase– Honk der Hase2016年07月20日 17:48:57 +00:00Commented Jul 20, 2016 at 17:48
-
sorry but i didn't understand you.Abderrahman Msd– Abderrahman Msd2016年07月20日 18:19:57 +00:00Commented Jul 20, 2016 at 18:19
-
it means: when you say "array[0].title" then the entry at offset 0 will become an objectHonk der Hase– Honk der Hase2016年07月20日 19:10:59 +00:00Commented Jul 20, 2016 at 19:10
-
i edited my code please have a look at itAbderrahman Msd– Abderrahman Msd2016年07月20日 20:04:23 +00:00Commented Jul 20, 2016 at 20:04
-
looks good, console.log() it and see what it really got.Honk der Hase– Honk der Hase2016年07月20日 21:59:08 +00:00Commented Jul 20, 2016 at 21:59
2 Answers 2
Looks like you can simply parse the json into your var props to create the array object...
var props = JSON.parse(json_obj);
props is now a js array object built from parsing your json string...
EDIT: proposed change to your js file
var props = [];
$.getJSON("results.json", function (data) {
$.each( data, function(index) {
props.push({title:data[index].name,Data:data[index].Description});
});
});
alert(props);
omit the rest of the code pushing to new array... just log out props...
3 Comments
You need to define array and push elements into it, why don't you try something like this
var someArray=[]
someArray.push({title:props[0].name,Data:props[0].Description})
someArray.push({title:props[1].name,Data:props[1].Description})
But its not a good idea if you donot know the length of props array
To convert json object into array you should loop through json object and push individual element into some array
var someArray = []
for(var key in json_object){
if(json_object.hasOwnProperty(key)){
var tmpObj={title:json_object[key].name,Data:json_object[key].Description}
someArray.push(tmpObj)
console.log(someArray)
}
}
Thanks