2
var text = '{ "employees" : [' +
'{ "id": 999, "username": "Batman" } ]}';

obj = JSON.parse(text);
var id = obj.employees[0].id;

Question is, how to access as in example above id, from javascript object? In example above it has "name" to gain access to id, which is employees. But real life example below i don't have "name" to use to gain id value.

var text = '{ "" : [' +
'{ "id": 999, "username": "Batman" } ]}';

obj = JSON.parse(text);
var id = obj.**WHAT TO PUT HERE TO ACCESS-->**.id;
0

2 Answers 2

7

you can access for empty string as a key and remember that is a array inside, use the item 0

obj[''][0].id
Sign up to request clarification or add additional context in comments.

Comments

1

You can avoid this situation by using an array of objects (removing the external curly braces) like

var text = '[{ "id": 999, "username": "Batman" } ]';

objs = JSON.parse(text);
var id = objs[0].id;
console.log(id); // 999

Comments

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.