我在处理JavaScript中的JSON数据时遇到问题,特别是在将数据用作数组以及访问和迭代各个值方面。JSON文件的结构如下:
{ "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" } } ] } }
我希望能够将其转换为如下所示的JavaScript数组,以便可以迭代它并按顺序提取每个位置的值:
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'] ];
有人对如何实现这一目标有任何建议吗?我已经尝试了以下方法,但是它在JSON中选择了“类型”,而不仅仅是值:
$.each(JSONObject.results.bindings, function(i, object) { $.each(object, function(property, object) { $.each(object, function(property, value) { value; }); }); });
任何帮助,建议,建议或更正将不胜感激。
var locations = []; $.each(JSONObject.results.bindings, function(i, obj) { locations.push([obj.place.value, obj.lat.value, obj.long.value, obj.page.value]); });
迭代通过bindings,并把该属性place.value,lat.value,long.value并page.value从每个元素到一个数组,再加入此数组locations。
bindings
place.value
lat.value
long.value
page.value
locations
您当前的代码使用和object两次property,从而覆盖这些变量。您应该在嵌套循环中使用唯一的变量名称,以便能够区分它们。
object
property