I’m having a problem handling JSON data within JavaScript, specifically in regards to using the data as an array and accessing and iterating through individual values. The JSON file is structured as follows:
{
"head": {
"vars": [ "place" , "lat" , "long" , "page" ]
} ,
"results": {
"bindings": [
{
"place": { "type": "literal" , "value": "Building A" } ,
"lat": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "10.3456" } ,
"long": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "-1.2345" } ,
"page": { "type": "uri" , "value": "http://www.example.com/a.html" }
} ,
{
"place": { "type": "literal" , "value": "Building B" } ,
"lat": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "11.3456" } ,
"long": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "-2.2345" } ,
"page": { "type": "uri" , "value": "http://www.example.com/b.html" }
} ,
{
"place": { "type": "literal" , "value": "Building C" } ,
"lat": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "12.3456" } ,
"long": { "datatype": "http://www.w3.org/2001/XMLSchema#float" , "type": "typed-literal" , "value": "-3.2345" } ,
"page": { "type": "uri" , "value": "http://www.example.com/c.html" }
}
]
}
}
I want to be able to convert this into a JavaScript array as follows in order that I can iterate through it and pull out the values for each location in order:
var locations = [
['Building A',10.3456,-1.2345,'http://www.example.com/a.html'],
['Building B',11.3456,-2.2345,'http://www.example.com/b.html'],
['Building C',12.3456,-3.2345,'http://www.example.com/c.html']
];
Does anyone have any advice on how to achieve this? I have tried the following, but it picks up the “type” within the JSON, rather than just the value:
$.each(JSONObject.results.bindings, function(i, object) {
$.each(object, function(property, object) {
$.each(object, function(property, value) {
value;
});
});
});
Any help, suggestions, advice or corrections would be greatly appreciated.
Iterate through
bindings, and put the propertiesplace.value,lat.value,long.valueandpage.valuefrom each element into an array, then add this array tolocations.Your current code uses
objecttwice, as well asproperty, thus overwriting those variables. You should use unique variable names in nested loops to be able to distinguish between them.