2

I have the following JSON returned from an AJAX call:

{"rows":[{"Date":"07/10/2011","Value":1206,"Action":"Drink"},    
{"Date":"07/11/2011","Value":2288,"Action":"Pie"},
{"Date":"07/12/2011","Value":1070,"Action":"Drink"},
{"Date":"07/13/2011","Value":1535,"Action":"Beer"},
{"Date":"07/14/2011","Value":1721,"Action":"Drink"}],
"page":1,"total":1,"records":5}

How can I get values from this result using jQuery?

For instance, I'd like to get data elements for the first row:

json.rows[0].date = 07/10/2011
json.rows[0].value = 1206

?

2 Answers 2

3

There are a number of ways to do this, you could use eval() but eval() is generally considered evil, plus JSON is not exactly the same as a defining data in Javascript code. I just googled which reminded me that jquery has a parseJSON function.

Check it out.

http://api.jquery.com/jQuery.parseJSON/

But if you are using jquery for the ajax ( pretty popular ), you can set the dataType to json and this will do it for you.

    $.ajax(
    {
            url: "/map", // should return JSON
            dataType: 'json',
            cache: false,
            data: {},
            success: function(response)
            {
                // response is an object

                alert( response.rows[0].Date );

                cook( response );
            }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the response. I am looking to use AJAX but just wondering how I actually get each row of data as an object ? i.e. if my data above is response do I simply var obj = response; and then use obj.rows[0].Date ?
yes, i think so, I have updated my answer, I hope it helps you to solve the problem.
0

jQuery.parseJSON

5 Comments

thanks for the reply. Little confused how to use this ? i.e. if my data above is data do I simply var obj = $.parseJSON(data); and then use obj.rows[0].data ?
Not sure about $.parseJSON but this works pretty well: var obj = jQuery.parseJSON(yourData); alert(obj.rows[0].Date);
OK thanks - and to iterate across each line ? i.e. so I can get each piece of data - how would I do this ?
Well, for (var i=0;i<obj.rows.length;i++) { alert(obj.rows[i].Date); }
dont't forget to catch errors.. try { var obj = jQuery.parseJSON(yourData); } catch(e){ ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.