Find value in json using javascript

I cannot find one way to get this value ("comment") in 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 am trying an example like this:

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

Can someone help me?

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

Tks a lot! Marqueti

+6
json javascript parsing
source share
2 answers

Your JSON is formatted in such a way that it is very difficult to read, but it looks like you are looking for:

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

This is because the object indicated by ...topicos[0] does not have a data key, but just a comment key. If you want further keys to go through, just go ahead: obj.topicos[0].comment.commentable_type .

Update

To find out which keys are in topicos[0] , you can do several approaches:

  • use the switch or, if you want:

     var topic = myJSONObject.topicos[0]; if( topic.hasOwnProperty( 'comment' ) ) { // do something with topic.comment } 
  • You may have cross-browser compatibility issues here, so it’s useful to use a library like jQuery , but overall you can map the properties like this:

     for( var key in myJSONObject.topicos[0] ) { // do something with each `key` here } 
+13
source share

This should work:

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

If you want, you can execute the loop as follows:

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

All Articles