0

I'm trying to figure out on how to access data in JSON format and have gone a whole day searching for ways but I still can't find a solution to fit my needs. The closest relative question to my problem is this question but to no avail.

Basically I am retrieving data from $.ajax() which returns in JSON format.

[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]

My problem is how can I access the elements inside the JSON, say I want to get all values of "nv" or all values of "date" on the second bracket, in javascript? I Am new at things like these so am not familiar with the terminologies, sorry for that.

Below is my code:

var Data = $.ajax({
    url: url,
    type: 'POST',
    dataType:"json",
    async: false
}).responseText;

console.log(Data);

url is a variable that is passed inside my function in case you might ask.

Community
  • 1
  • 1
Darth
  • 433
  • 4
  • 14
  • 3
    JSON represents a single object or array, so you can't return two entirely separate arrays. How would that work when you parse it to an actual object/array stored in a variable? One variable can't point to two separate things. – Anthony Grist Feb 22 '13 at 09:59
  • @AnthonyGrist is right. Your json string is not valid. Check it in http://jsonlint.com/ – Kris Feb 22 '13 at 10:12
  • @Kris thanks for the link, I guess I need to reconstruct my json string. – Darth Feb 22 '13 at 10:14

2 Answers2

4

Update: See Anthony Grist's comment on your question, I missed the fact that your JSON is invalid. Since he hasn't posted an answer, I'll pick it up.

Your JSON is invalid because you're returning two separate arrays, this one:

[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]

and this one:

[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]

You can't do that, because the top level of a JSON document must be one thing (an object or an array).

You could return an object with properties for each array:

{
"vdata":
    [{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
     {"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
     {"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
    ],
"datedata":
    [{"date":"2013-02-01","visits":63},
     {"date":"2013-02-02","visits":30}
    ]
}

After parsing (see below), you can access that data like this:

console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"

Or an array with two slots, with each slot having one of your arrays in it:

[
    [{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
     {"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
     {"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
    ],
    [{"date":"2013-02-01","visits":63},
     {"date":"2013-02-02","visits":30}
    ]
]

After parsing (see below), you can access that data like this:

console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"

Personally, I prefer using an object, since then it's clear which array I'm accessing.


Original answer:

jQuery will parse the JSON into an object for you and pass that to the success function, which you can then access just like any other object. In your case, the top level is an array. So:

$.ajax({
    url: url,
    type: 'POST',
    dataType:"json",
    async: false,
    success: function(data) {
        // Use the line from above that suits the way
        // you updated your JSON structure
    }
});

Side note: async: false is deprecated and will be removed at some point. It's generally not a good idea to do synchronous ajax requests, it tends to lock up the UI of the browser during the request. Instead, just structure your code to continue processing when the success callback is triggered.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks @Crowder for answering but for some odd reason there is no data displayed on the log. I've tried putting up a simple `alert()` function under the `success` callback to check but even that did not triggered. Any ideas on how to troubleshoot? – Darth Feb 22 '13 at 09:43
  • 1
    @Darth: I thought from your question that you were successfully seeing the JSON come back, but it sounds like you weren't. That suggests that you're doing a cross-origin call and being blocked by the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy), which prohibits cross-origin calls. If the other end supports it, you could switch to using [JSONP](http://en.wikipedia.org/wiki/JSONP#JSONP), which bypasses the SOP, or (if, again, the source supports it) [CORS](http://www.w3.org/TR/access-control/). But CORS also requires browser support. – T.J. Crowder Feb 22 '13 at 09:53
  • @Crowder yep I can display the returned JSON in the log with `console.log(Data)` which is odd. – Darth Feb 22 '13 at 09:59
  • @Darth Try adding an `error` function to the call to `$.ajax()`, that way you can see if there are any problems handling the response. – Anthony Grist Feb 22 '13 at 10:02
  • @Anthony Thanks for the `error` callback, will check on that. – Darth Feb 22 '13 at 10:11
  • @Darth: Anthony Grist picked up the problem, your JSON is invalid. I've updated the answer to explain how to fix it. – T.J. Crowder Feb 22 '13 at 10:19
  • @Crowder thanks for the clear explanation, that explains why am having a hard time looking for an answer. – Darth Feb 22 '13 at 10:21
  • @Darth: No worries, I've updated further to show how to access the data in each case. – T.J. Crowder Feb 22 '13 at 10:26
1

If I understand your problem you need to access the same key for all objects in this array.

There is no direct method to do that, you have to iterate through all objects in this array and then find the desired key in each of those objects.

JSON.parse() will convert this string into a Javascript Object (JSON)

var myData = JSON.parse(Data);

for(var i = 0; i < myData.length; i++) {
    console.log("This is the nv value of the " + i + " object: " + myData[i].nv);
}
enricoide
  • 83
  • 1
  • 9
  • yep that's right, i need to access the same key for all objects. but following your code gave me this error: `SyntaxError: JSON.parse: unexpected character` `var myData = JSON.parse(Data);` – Darth Feb 22 '13 at 09:52
  • @Darth: `
    ` is in your error message or is part of the error? I think is not part of the error, so maybe you have no data in your Data variable. Instead of the `success` callback you can try the `error` callback or the `complete` callback to find out what's happening here.
    – enricoide Feb 22 '13 at 10:01
  • `
    ` is not part of my error message, just messed up my comment a while ago. Thanks for the `error` and `complete` callback, will check on that.
    – Darth Feb 22 '13 at 10:10