0

I have a requirement to read JSON data in my application. Problem is that the JSON data that I am getting from the service includes "-" and when I am trying to read it, I am getting "Uncaught ReferenceError: person is not defined ". e.g.

I have below JSON object-

 var JSONObject ={
 "name-person":"John Johnson",
 "street":"Oslo West 16", 
 "age":33,
 "phone":"555 1234567"};

when I am writing below console log statement I am getting "Uncaught ReferenceError: person is not defined " error

  console.log(JSONObject.name-person);

Can someone please help me how to read such data which includes "-" in it? I do not have control on the service and the DB so to modify source data is not in my hand.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Anil kumar
  • 525
  • 2
  • 10
  • 32

2 Answers2

2

Try this way: JSONObject["name-person"]

A JSON is an object, which is composed by key-value pairs, an object key can have any character or even reserved keywords (like for, function, if...), to access an object item by its key when it doesn't obbey the rules for a valid identifier (http://coderkeen.com/old/articles/identifiers-en.html), you have to use [ ].

Here's a funny example of what I'm talking about:

var strangeObject = {" ...this is a TOTALLY valid key!!! ": 123, 
                   "function": "what a weird key..."};

console.log(strangeObject [" ...this is a TOTALLY valid key!!! "], 
            strangeObject ["function"]); 
Alcides Queiroz
  • 9,456
  • 3
  • 28
  • 43
1

Use the [] syntax to access the property.

JSONObject['name-person']
plalx
  • 42,889
  • 6
  • 74
  • 90