Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find value in Json by javascript

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

like image 540
mmarqueti Avatar asked Nov 09 '09 21:11

mmarqueti


2 Answers

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
    }
    
like image 70
rfunduk Avatar answered Sep 23 '22 05:09

rfunduk


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]);
}
like image 28
Greg Avatar answered Sep 22 '22 05:09

Greg