Lexx
Lexx

Reputation: 735

Access Json Object

I have a json object(jsencodedata) that is printed in Javascript like that:

document.write(jsencodedata); 

It prints:

[{"user":"John","Pass":"abc123"},{"user":"John2","Pass":"abcdef"}]

My question is how to get only the first user or password or only the second one? I'm new to this, so please excuse me for the stupid question?

Upvotes: 1

Views: 125

Answers (3)

TachyonVortex
TachyonVortex

Reputation: 8602

Assuming you are using a browser with native JSON support, then:

var arrData = JSON.parse(jsencodedata);

will parse the JSON string into an array, and then:

arrData[0] is the first user.
arrData[0].user is the first user's name.
arrData[0].Pass is the first user's password.

arrData[1] is the second user.
arrData[1].user is the second user's name.
arrData[1].Pass is the second user's password.

Upvotes: 0

theabraham
theabraham

Reputation: 16400

Try this (assuming jsencodeddata is a JSON string):

var users = JSON.parse(jsencodeddata);
console.log(users[0]); // the first user object
console.log(users[1]['Pass']); // second user's password

That will convert the JSON string into an actual array of objects.

Upvotes: 3

Dillon Benson
Dillon Benson

Reputation: 4440

Try

jsencodedata[0].user;  //returns "John"
jsencodedata[0].Pass;  //returns "abc123"

The array indices tell you what object to access [0] means you are accessing the first object and [1] means you are accessing the second object.

Upvotes: 0

Related Questions