Abderrahman Msd Abderrahman Msd - 12 days ago 6
Javascript Question

Reading & Transforming JSON Object into Javascript Array

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);
});

Tim Tim
Answer

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...