David
David

Reputation: 55

JavaScript JSON object with square brackets and spaces in name

I have encountered a JSON Structure I have never seen before. This is using Square Bracket ([]) but has spaces in the name. How would I navigate such a structure?

"profile": [{
  "[Profile ID]": 1001398965,
  "[Name | Prefix]": "Ms.",
  "[Name | First]": "Lori",
  "[Name | Middle]": "",
  "[Name | Last]": "Smith",
  "[Name | Suffix]": "",
  "[Contact Name]": "Lori Smith"
},
{  "[Profile ID]": 1001398965,
  "[Name | Prefix]": "Ms.",
  "[Name | First]": "Jeanine",
  "[Name | Middle]": "",
  "[Name | Last]": "Samson",
  "[Name | Suffix]": "",
  "[Contact Name]": "Jeanine Samson"
}]

I have tried

profile[0]['Name | First']  //result undefined

profile[0][Name | First]   //result Name is not defined

Any help is appreciated.

Upvotes: 1

Views: 746

Answers (2)

tom
tom

Reputation: 10581

j['profile'][0]['[Name | Prefix]']

See this snippet:

var j = {
  "profile": [{
    "[Profile ID]": 1001398965,
    "[Name | Prefix]": "Ms.",
    "[Name | First]": "Lori",
    "[Name | Middle]": "",
    "[Name | Last]": "Smith",
    "[Name | Suffix]": "",
    "[Contact Name]": "Lori Smith"
  },
  {  "[Profile ID]": 1001398965,
    "[Name | Prefix]": "Ms.",
    "[Name | First]": "Jeanine",
    "[Name | Middle]": "",
    "[Name | Last]": "Samson",
    "[Name | Suffix]": "",
    "[Contact Name]": "Jeanine Samson"
  }]
};

console.log(j['profile'][0]['[Name | Prefix]']);

Upvotes: 1

Raphaël
Raphaël

Reputation: 3751

Brackets are part of the key. You have to use:

profile[0]['[Name | First]']

Upvotes: 1

Related Questions