我在AS3中解析JSON文件时遇到问题。我试图解析多个JSON数组,但在访问第一个JSON数组后却不知道如何进入下一个。我的JSON文件如下:
{
"term": [
{
"id": 4211,
"place": "NEW YORK CITY"
},
{
"id": 2675,
"place": "WASHINGTON (DC)"
}
],
"term": [
{
"id": 4211,
"place": "NEW YORK CITY"
},
{
"id": 2675,
"place": "WASHINGTON (DC)"
}
]
}
我的AS3代码如下:
public function parseData(e:Event):void
{
var loader:URLLoader = URLLoader(e.target);
var values:Object = JSON.decode(loader.data);
var term:Array = values.term;
var counter:Number = 0;
for (var key:Object in term)
{
payload[counter] = [term[key].id, term[key].place];
counter++;
}
dispatchEvent(new Event(Event.COMPLETE));
}
我可以从第一个数组中获取数据,但是如何构建我的代码以便我可以遍历2个或更多“term”数组?
由于
答案 0 :(得分:6)
JSON(或任何其他有序映射类型)无法保存重复键。
解决方案是将JSON重组为:
{
"terms": [
[
{
"id": 4211,
"place": "NEW YORK CITY"
},
{
"id": 2675,
"place": "WASHINGTON (DC)"
}
],
[
{
"id": 4211,
"place": "NEW YORK CITY"
},
{
"id": 2675,
"place": "WASHINGTON (DC)"
}
]
]
}
答案 1 :(得分:3)
我注意到的一件事是你的JSON有点奇怪并导致你的错误。您的JSON的主要类是定义该术语两次的字典。这不会导致错误,但会导致第二次覆盖values.term。您应该将JSON更改为:
{
"term": [[
{
"id": 4211,
"place": "NEW YORK CITY"
},
{
"id": 2675,
"place": "WASHINGTON (DC)"
}],
[{
"id": 4211,
"place": "NEW YORK CITY"
},
{
"id": 2675,
"place": "WASHINGTON (DC)"
}]
]
}
和您的代码:
public function parseData(e:Event):void
{
var loader:URLLoader = URLLoader(e.target);
var values:Object = JSON.decode(loader.data);
var term:Array = values.term;
var counter:Number = 0;
for (var keys:Object in term)
{
for (var key:Object in term[keys])
{
payload[counter] = [term[keys][key].id, term[keys][key].place];
counter++;
}
}
dispatchEvent(new Event(Event.COMPLETE));
}