parse variable as JSON w/ jQuery

2.3k Views Asked by At

I am trying to populate a form with a list of questions and radio buttons. When the page is loaded I have a variable that contains the answers they have so far as a string in JSON format:

var json = '{ "answers" : [{"84" : "Y" },{"85" : "Y" },{"86" : "Y" },{"87" : "Y" },{"88" : "Y" },{"89" : "N" },{"90" : "N" },{"91" : "N" },{"92" : "Y" },{"93" : "N" },{"94" : "Y" },{"95" : "N" },{"96" : "N" },{"97" : "Y" }]}';

I need to loop through the answers and find the radio button with the ID matching the number IE id="84" and set it's value based on the corresponding value (Y).

seems like getJSON is what I should be looking at but I do not need to make the call to get the data since I already have it.

3

There are 3 best solutions below

0
On BEST ANSWER

Got it, removed the quotes as mentioned above added a class that matched the ID so I could select all elements for a given ID:

 for(var i =0; i < json.answers.length; i++) { 
           var item = json.answers[i]; 
           for (var j in item) {
              $('.' + j).each(function(){
                 if ($(this).attr("value") == item[j]) $(this).attr("checked", true);
              });
     }
 }

I am sure there is probably a more elegant solution but this is working very well so far.

0
On

Normally you would just use a each statement like below:

 jQuery.each(json.answers, function(i, val) {
   $("#" + i).val() = val;
 });
3
On

You could just remove the quotes on the outside and it would already be in the right format.

var json = {
                "answers" : [{"84" : "Y" },
                 {"85" : "Y" },
                 {"86" : "Y" },
                 {"87" : "Y" },
                 {"88" : "Y" },
                 {"89" : "N" },
                 {"90" : "N" },
                 {"91" : "N" },
                 {"92" : "Y" },
                 {"93" : "N" },
                 {"94" : "Y" },
                 {"95" : "N" },
                 {"96" : "N" },
                 {"97" : "Y" }
            ]
        };

Unlike some other formats, JSON is based on the actual language, which means that you can use the JSON format in regular coding. It is fairly easy to write JSON.