通过javascript在Json中查找值

通过javascript在Json中查找值,javascript,json,parsing,Javascript,Json,Parsing,我找不到一种使用javascript将该值(“注释”)转换为json的方法 var myJSONObject = { "topicos": [{ "comment": { "commentable_type": "Topico", "updated_at": "2009-06-21T18:30:31Z", "body": "Claro, Fernando! Eu acho isso um extr

我找不到一种使用javascript将该值(“注释”)转换为json的方法

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"
        }
    }]
};
我正在尝试这样一个例子:

alert(myJSONObject.topicos[0].data[0]);
for (var key in myJSONObject.topicos[0])
{
   alert(key);
   if (key == 'comment')
    alert(myJSONObject.topicos[0][key]);
}
有人能帮我吗

json来自RubyonRails应用程序,使用
render:json=>@atividades.to_json

太多了! Marqueti

您的JSON格式很难阅读,但在我看来,您正在寻找:

alert( myJSONObject.topicos[0].comment );
这是因为
…topicos[0]
给出的对象中没有
数据
键,而只有键
注释
。如果您想要更多的键通过,只需继续如下操作:
obj.topicos[0]。comment.commentable\u type

更新

要了解topicos[0]中的键,可以采取以下几种方法:

  • 使用开关或类似装置:

    var topic = myJSONObject.topicos[0];
    if( topic.hasOwnProperty( 'comment' ) ) {
      // do something with topic.comment
    }
    
  • 此处可能存在跨浏览器兼容性问题,因此使用类似的库会有所帮助,但通常您可以映射以下属性:

    for( var key in myJSONObject.topicos[0] ) {
      // do something with each `key` here
    }
    
  • 这应该起作用:

    alert(myJSONObject.topicos[0].comment);
    
    如果需要,可以这样循环:

    alert(myJSONObject.topicos[0].data[0]);
    
    for (var key in myJSONObject.topicos[0])
    {
       alert(key);
       if (key == 'comment')
        alert(myJSONObject.topicos[0][key]);
    }
    

    为了更进一步,您可以执行如下操作:alert(myJSONObject.topicos[0].comment.commentable\u type);谢谢你的回复。我需要获取键“comment”字符串。因为我也可以收到另一种。类似于这样的内容:myJSONObject.topicos[0]。您可以访问myJSONObject.topicos[0]。支持,然后我将执行一些设置正确输出格式的操作。tks!