0

I have this multiple set of data as array

data = [{"id": "1", "name" : "abc", "key1" : "value12 }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]

I need to get this data using jQuery

json = $.parseJSON(data);

but how do I access the parsed JSON data? json.id shows the result as undefined.

Thanks

Update : Sorry I fixed the above example JSON I gave, I just quickly typed it by myself and it's not the original json I'm having trouble with. I just gave it to give an idea about the problem that I was having. Thanks for the answers :)

2
  • 2
    That looks like invalid JSON to me. There should be commas in between each object. You have an array of objects. Accessing the id of the first object in the collection would be json[0].id. Commented Dec 13, 2013 at 17:23
  • @cpreid sorry about that, i fixed the json, i just typed it myself, the original json is json_encode by php so the original JSON is not wrong, i just made an example to give an idea about the question Commented Dec 13, 2013 at 17:28

4 Answers 4

3

It isn't JSON. It isn't even JavaScript.

If you fix the syntax errors (such as the missing quotes and the missing commas between the array items) then it is an array literal (containing object literals which contain …). Don't parseJSON it (you use that on JSON texts stored in JavaScript strings).

Since it is an array. It doesn't have an id. It has a number of numerical indexes.

var someObject = data[0];

The objects stored on those indexes have ids.

var id = someObject.id;
Sign up to request clarification or add additional context in comments.

Comments

0

Your json is invalid. ',' are missing between objects.

Suppose if json is :

data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }]

Then you can access 'id' element using this :

data[0].id

Comments

0

Try this:

var data = '{"id": "1", "name" : "abc", "key1" : "value12" } , {"id": "2", "name" : "cde", "key2" : "value2"}';
var obj = JSON.parse('[' + data + ']');
alert(obj[0].id);

Here is demo

Comments

-1

Your json is invalid,

data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]

Retrive using:

var id =  data[0].id;

console.log(id);

1 Comment

Mr.Downvoters, May I know the reason for Downvoting?

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.