Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 31393  / 15 Years ago, mon, november 9, 2009, 12:00:00

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 atu00e9 filmam, poderu00edamos achar um jeito de ter postos de denu00fancia que receberiam esses vu00eddeos e recolheriam os motoristas paressadinhos para um treinamento. O que vocu00ea 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


More From » json

 Answers
29

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
    }


[#98350] Thursday, November 5, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeniferjaliyahf

Total Points: 650
Total Questions: 104
Total Answers: 86

Location: Grenada
Member since Sun, Dec 20, 2020
4 Years ago
;