0
{
    "status":"success",
    "data":
        {
            "title":"Testing",
            "token":"77fl",
            "questions":
                [{
                    "title":"How are you?",
                    "token":"UHGXI",
                    "kind":"multiple-choice",
                    "options":
                        [{
                            "content":"Good",
                            "token":"tLAzWd",
                            "kind":"text"
                         },
                    {
                          "content":"bad",
                          "token":"8LRR3t",
                          "kind":"text"
                     }]}]}}

I've never parsed JSON data before... what is a good first step sort of thing to parse this? I obviously don't need all of this, I need all instances of 'title', 'kind', and 'content'.

Do you do it similar to parsing a string?

This is my function to grab it...

$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("http://quicksurvey.herokuapp.com/api/surveys/77fl/ask.json",function(result){
      });
    });
  }); 
});

Where is my returned data stored exactly? Is it in 'result'?

I'm very new to all of this so I apologize if I'm making some obvious mistakes. I've been looking around for answers to my question but can't find an easy introduction to this. I'd like to parse using javascript.

Hoser
  • 4,974
  • 9
  • 45
  • 66

2 Answers2

3

The answer is yes, it is stored inside of result. The jQuery function takes the returned JSON string and converts it back into a native javascript object that represents the said string. If you didn't return the json string with a name then the result variable will be the object itself. But in your case, you named the object data so you should access it like:

$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("http://quicksurvey.herokuapp.com/api/surveys/77fl/ask.json",function(result){
         //result.data 
         //result.status
      });
    });
  }); 
});
Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
1

Yes you can, just parse it as an jSON object. You can access properties and arrays as a javascript object or properties. Fiddle

JS Version

for(var i =0; i<result.data.questions.length; i++)
{
    alert(result.data.questions[i].title + ' ' + result.data.questions[i].kind);
}

Jquery:-

alert(result.data.title);
$.each(result.data.questions,function(i,o){
    alert(o.title + ' ' + o.kind);
});
PSL
  • 123,204
  • 21
  • 253
  • 243
  • 1
    Why downvote? A comment would be useful, an anonymous down vote can't improve anything.... – PSL Apr 15 '13 at 05:12
  • Not sure why you got a downvote but the looping method worked great for me! I appreciate the help. I wish I could give two people credit for helping me out – Hoser Apr 15 '13 at 05:22
  • Thanks for who-ever reversed the downvote :) – PSL Apr 15 '13 at 16:08