使用 JQuery 解码 JSON
我对 jquery 的探索被证明有点令人沮丧。
我从服务器收到以下 Json。
{"status":"ok",
"0":{"ID":"1","location":"location info"},
"1":{"ID":"2","location":"location info"},
"2":{"ID":"3","location":"location info"},
...etc
});
我需要将除状态之外的所有对象放入一个数组中。 我在 AS3 中实现了这一点,如下所示,但似乎无法使用 jquery 获得任何接近的结果。
public function ResultToArray(jsonString:String):Array
{
var jObj:Object = JSON.decode(jsonString);
var objects:Array = [];
for each(var obj:Object in jObj)
{
if(obj is String)break;
objects.push(obj);
}
return objects;
}
我想将每个对象放入一个数组中。
以下仅循环一个对象。
$(data).each(function(index)
{
alert(data[index]["location"])
});
请原谅我的无知。 如果我能收到任何建议,我将不胜感激。
my explorations into jquery are proving a little frustrating.
I am receiving the following Json back from the server.
{"status":"ok",
"0":{"ID":"1","location":"location info"},
"1":{"ID":"2","location":"location info"},
"2":{"ID":"3","location":"location info"},
...etc
});
I need to put all the objects except the status into an array.
I achieved this in AS3 as follows, but don't seem to be able to get any where near using jquery.
public function ResultToArray(jsonString:String):Array
{
var jObj:Object = JSON.decode(jsonString);
var objects:Array = [];
for each(var obj:Object in jObj)
{
if(obj is String)break;
objects.push(obj);
}
return objects;
}
I would like to put each of the objects in an array.
The following only loops over one object.
$(data).each(function(index)
{
alert(data[index]["location"])
});
Please pardon my ignorance.
If I could receive any advice It'd be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解得很好,你的 JSON 可以改进来帮助你。与其将每个位置存储为从零开始的整数索引,为什么不将它们存储在 JSON 数组中:
然后,使用 jQuery,您需要做的就是解析 JSON 并提取
location
参数,即已经是一个数组:If I understand well, your JSON could be improved to help you out here. Instad of storing each location as a zero-based integer index, why not store them in a JSON array:
Then, with jQuery all you need to do is parse the JSON and extract the
location
parameter, which is already an array:如果您不想检查“状态”,可能可以检查
(typeof o[c] == 'object')
。Possibly you could check
(typeof o[c] == 'object')
if you don't want to check for 'status'.您可以使用 jQuery.getJSON() 远程获取数据并将其转换为 Javascript 对象。
You can use jQuery.getJSON() to fetch data remotely and have it turned into a Javascript object.