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.
var locations = [];
$.each(JSONObject.results.bindings, function(i, obj) {
locations.push([obj.place.value, obj.lat.value, obj.long.value, obj.page.value]);
});
Iterate through bindings
, and put the properties place.value
, lat.value
, long.value
and page.value
from each element into an array, then add this array to locations
.
Your current code uses object
twice, as well as property
, thus overwriting those variables. You should use unique variable names in nested loops to be able to distinguish between them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With