vee
vee

Reputation: 69

reading JSON element using JS

I am receiving a JSON object from a PHP get request. It looks like this:

data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

eti=data["emp_type_id"];
var myVar = eti[0];

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

Upvotes: 2

Views: 257

Answers (5)

no.good.at.coding
no.good.at.coding

Reputation: 20371

var eti = data.emp_type_id;
var myVar = eti[0];

for(var key in myVar){
    myVar[key];
}

Upvotes: 0

epascarello
epascarello

Reputation: 207501

use a for in loop

var data = {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]};
var eti = data["emp_type_id"];
var myVar = eti[0];
for(var entry in myVar){
  alert(entry + ":\t" + myVar[entry] );
}

Running JSBIN Example

Upvotes: 2

James
James

Reputation: 22247

data is an object that has two properties, user_id and emp_type_id. emp_type_id is an array with one element (???), that element is an object with the properties 0 and 1.

There are two ways of reading a property from an object:

var prop = data['emp_type_id'];
var prop = data.emp_type_id;

If you have "weird" property names then you will have to use the square-bracket technique.

so

var prop0 = data.emp_type_id[0].0;
var prop1 = data.emp_type_id[0].1;

I'm concerned that "0" and "1" will fall under the category of "weird property names" so you might need to do

var prop0 = data.emp_type_id[0]["0"];
var prop1 = data.emp_type_id[0]["1"];

Upvotes: 1

Hogan
Hogan

Reputation: 70523

Neal's answer will help, but I think you have other problems. Your json structure looks wrong

a) data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

should it be

b) data == {"user_id":"7","emp_type_id":["11","10"]}

That is in english

a) emp_type_id an array of one object which has two fields 0 and 1?

b) emp_type_id an array of two items with values 11 and 10

If it should be b) then your json is wrong.

Upvotes: 1

Naftali
Naftali

Reputation: 146300

Try this:

var eti = data.emp_type_id;
var myVar = eti[0];

Upvotes: 0

Related Questions