7

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?

The json is from Ruby On rails application, using render :json => @atividades.to_json

Tks a lot! Marqueti

Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
mmarqueti
  • 257
  • 1
  • 5
  • 8

2 Answers2

13

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 );

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.

Update

To find out what keys are in topicos[0] you can take a couple approaches:

  1. use a switch or if like:

    var topic = myJSONObject.topicos[0];
    if( topic.hasOwnProperty( 'comment' ) ) {
      // do something with topic.comment
    }
    
  2. 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
    }
    
rfunduk
  • 30,053
  • 5
  • 59
  • 54
  • to take it a step farther, you could do something like: alert(myJSONObject.topicos[0].comment.commentable_type); – Mercurybullet Nov 09 '09 at 21:42
  • Tks for the replies. I need to get the key "comment" string. Because I can receive another type too. Something like this: myJSONObject.topicos[0].people ou myJSONObject.topicos[0].support And then I will do some If to format the correct output. tks ! – mmarqueti Nov 09 '09 at 21:48
1

This should work:

alert(myJSONObject.topicos[0].comment);

If you want you can loop through like this:

for (var key in myJSONObject.topicos[0])
{
   alert(key);
   if (key == 'comment')
    alert(myJSONObject.topicos[0][key]);
}
Greg
  • 316,276
  • 54
  • 369
  • 333