在控制器上,我的代码如下:
format.json {render :json=>{
:entities => @entities,
:entity_category_counters => @entity_category_counters
}}
在浏览器方面,我的代码如下:
$.getJSON('/entities.json',function(data){
//data.entities
//data[0].entities
//data['entities']
});
无论我使用哪种方式访问返回JSON对象的数据,我都无法成功。
返回的JSON类似于:
{ “实体”:[{ “实体”:{ “created_at”: “2011-08-01T18:14:32Z”, “描述”: “XXX”}},{ “实体”:{ “created_at” : “2011-08-01T18:16:02Z”, “描述”: “XXX”}}], “entity_category_counters”:[{ “entity_category_counter”:{ “comment_category_id”:1, “计数器”:4 “ENTITY_ID” :1, “ID”:1, “important_tag”:假}},{ “entity_category_counter”:{ “comment_category_id”:2 “计数器”:0, “ENTITY_ID”:1, “ID”:2 “important_tag” :假}},{ “entity_category_counter”:{ “comment_category_id”:3 “计数器”:0, “ENTITY_ID”:1, “ID”:3 “important_tag”:假}},{ “entity_category_counter”:{” comment_category_id “:1,” 计数器 “:3”,ENTITY_ID “:2”,ID “:4”,important_tag “:假}},{” entity_category_counter “:{” comment_category_id “:2”,计数器 “:0,” ENTITY_ID “:2”,ID “:5”,important_tag “:假}},{” entity_category_counter “:{” comment_category_id “:3”,计数器 “:1,” ENTITY_ID “:2”,ID “:6,” important_tag“:假}}]}
如果我直接使用Alert显示数据,如下所示:
$.getJSON('/entities.json',function(data){
//data.entities
//data[0].entities
//data['entities']
alert(data);
});
消息框中的结果如下:
[object Object],[object Object]
那么有人能告诉我如何解析和访问包含两个对象的返回JSON对象中的数据吗?提前谢谢!
答案 0 :(得分:3)
JSON代表JavaScript Object Notation,因此您现在正在使用纯JavaScript。你可以这样做:
data.entities[0].entity.created_at // 2011-08-01T18:14:32Z
我认为令人困惑的是,实体是一个数组,因此您必须访问该数组的索引才能获得其中的实体。然后你还有实体类别。
我认为你会发现一些有用的东西:
test = {"entities...