I am trying to use the data I have received from a php script, which was json_encode’d, but I just don’t seem able to get it right.
This is the javascript function I am using
JS:
function dispJSON(items) {
console.log('Raw from PHP:' + items);
var strJSON = JSON.stringify(items);
console.log('Sent from PHP and stringified:' + strJSON);
$('#results').append(strJSON + '<hr>');
var opStr = '';
for (i=0; i<items.length; i++){ //Get each Record
console.log('REC=' + items[i].tostring);
for (var key in items[i]) {
console.log(key + ' => ' + items[i][key]);
}
}
}
and this is what the console says.
Console:
WCIT.html:60 Sent from PHP and stringified:[[{"vehGrpName":"Austin","vehTitle":"Austin A30 (AS3 and AS4)","vehDescrip":"The new look Baby Austin to rival the Morris Minor."}],[{"vehGrpName":"Austin","vehTitle":"Austin A35","vehDescrip":"An improved A30. Better brakes, gearbox and engine."}]]
WCIT.html:64 REC=undefined
WCIT.html:66 0 => [object Object]
WCIT.html:64 REC=undefined
WCIT.html:66 0 => [object Object]
So I have obviously misunderstood some basics. My javascript / json knowledge is very limited.
I seem to be getting One Array (All the records), made up of two arrays (ie each record, which contains a json object of the record)
My code is obviously garbage, so if anyone can put me right, I would be most grateful.
Thanks
In your
dispJSONfunction, you’re no longer dealing with JSON (which is a textual data notation) at all — something somewhere along the line has deserialized it for you (which is handy). You’re dealing with the resulting array. From the look of the stringified copy, it’s an array of arrays, and each entry in the sub-arrays (which oddly only have one entry each) is an object with various properties:(jsonlint is handy for pretty-printing structures.)
So you’ll want to loop through that and deal with each of the sub-arrays and their entries (live copy):
Or if you don’t want to have the entry keys in your code (live copy):
That works because
for..inloops through the names of the properties in an object (as well as the property names of any of its prototype objects), and because you can refer to an object property in two different ways: In the familiarobj.propNameform wherepropNameis a literal, or in theobj["propName"]form, where the property name is a string. And of course, since it’s a string, it can be the result of any expression.Separately: You might want to find out why your PHP code is creating the sub-arrays with one entry each…