0

I'm receiving a JSON object that looks similar to this and keep coming up with undefined when trying to get the employer name:

{
name: 'Freddy Krueger',
birthdate: 'March 16, 2015',
email: 'email@domain.com',
'employer[name]': 'Some Employer, Inc',
'employer[address]': '1428 Elm St. Springwood, OH 00666'
}

How am I supposed to access the employer data? obj.name, obj.birthdate, etc is no problem. But obj.'employer[name]' doesn't work, of course. I've tried every version I can think of obj.employer['name'] is no good, I get an error that says TypeError: Cannot read property 'name' of undefined Seems like something silly, but everything I google for only mentions using quotes in your values and such and brackets are for arrays. Nothing related to getting data that has single quotes and brackets in the name of the pair.

I've seen their structure, to match this, it would look like:

{
"name": "Freddy Krueger",
"birthdate": "March 16, 2015",
"email": "email@domain.com",
"employer": {
    "name": "Some Employer, Inc",
    "address": "1428 Elm St. Springwood, OH 00666"
}
}

There's more data, but this shows the part I'm having issues with. Sometimes, "employer" will have a phone, fax, email, website, etc in it as well. It still looks the same as my first example, just with the new pairs added as 'employer[whatever]': 'value'

sdouble
  • 1,055
  • 3
  • 11
  • 28
  • In this case your property name in quotes would be considered as string type. The other object notation is correct to get the data. However if you cant change the coming JSON then we can write a method to process property name and create in the right structure. – Vaibhav Mar 16 '15 at 06:39
  • What you posted is not JSON. – Felix Kling Mar 16 '15 at 06:52

2 Answers2

2

Use the object notation:

 var employerName = obj['employer[name]'];
 var employerAddress = obj['employer[address]'];

Working example: http://jsfiddle.net/rbsdp4f2/

Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28
0

In order to get name you have to do

`obj["employer[name]"]` 

and not

obj."employer[name]"
Bikas
  • 2,709
  • 14
  • 32