通过javascript在Json中找到价值 [英] Find value in Json by javascript
问题描述
我找不到一种方法可以使用javascript将此值(注释)转换为json。
I cant find one way to get this value ("comment") into json using javascript.
var myJSONObject = {
"topicos": [{
"comment": {
"commentable_type": "Topico",
"updated_at": "2009-06-21T18:30:31Z",
"body": "Claro, Fernando! Eu acho isso um extremo desrespeito. Com os celulares de hoje que at\u00e9 filmam, poder\u00edamos achar um jeito de ter postos de den\u00fancia que receberiam esses v\u00eddeos e recolheriam os motoristas paressadinhos para um treinamento. O que voc\u00ea acha?",
"lft": 1,
"id": 187,
"commentable_id": 94,
"user_id": 9,
"tipo": "ideia",
"rgt": 2,
"parent_id": null,
"created_at": "2009-06-21T18:30:31Z"
}
}]
};
我正在尝试这样的例子:
I'm trying a example like this:
alert(myJSONObject.topicos[0].data[0]);
有些机构可以帮助我吗?
Some body can help me?
json来自Ruby On rails应用程序,使用 render:json => @ atividades.to_json
The json is from Ruby On rails application, using render :json => @atividades.to_json
很多!
Marqueti
Tks a lot! Marqueti
推荐答案
您的JSON格式化方式非常难以阅读,但是它看起来像你在寻找:
Your JSON is formatted in such a way that it is very hard to read, but it looks to me like you're looking for:
alert( myJSONObject.topicos[0].comment );
这是因为没有数据
键在 ... topicos [0]
给出的对象中,而只是键注释
。如果你想要更多的密钥,只需继续: obj.topicos [0] .comment.commentable_type
。
This is because there is no data
key in the object given by ...topicos[0]
, but rather just the key comment
. If you want further keys past that just continue like: obj.topicos[0].comment.commentable_type
.
更新
查找 c>主题中的键[0] 你可以采取几种方法:
To find out what keys are in topicos[0]
you can take a couple approaches:
-
使用开关或如果:
use a switch or if like:
var topic = myJSONObject.topicos[0];
if( topic.hasOwnProperty( 'comment' ) ) {
// do something with topic.comment
}
此处可能存在跨浏览器兼容性问题,因此请使用 jQuery等库会有所帮助,但一般情况下你可以像这样映射属性:
You might have issues with cross browser compatibility here, so using a library like jQuery would be helpful, but in general you can map over the properties like so:
for( var key in myJSONObject.topicos[0] ) {
// do something with each `key` here
}
这篇关于通过javascript在Json中找到价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!