Access to json is returning error

Asked

Viewed 34 times

3

I have the following json:

x = {
    "body-json": {
        "id": "1"
    }
}

I’m trying to access the id this way:

console.log(x.body-json.id);

Turns out I can’t access the reference body-json. Can someone help me?

  • Javascript uses Camelcase. Always try to use the first minuscule letter and when it’s another word, capitalize it. Example : bodyJson

1 answer

5


You need to use the following syntax to access your object:

console.log(x["body-json"].id)

How the expression x.body-json.id is interpreted as x.body - json.id according to the Javascript syntax rules. To access the variable you want, you need to use the syntax that passes the property name as a string.

  • 1

    With the - in the property name you cannot use the simple syntax of access to the object property.

  • I was wrong, it works. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.