2

I have a JSON-formatted document like so:

{
    "the-field": "something",
    // etc
}

When I call foo = JSON.parse() it spits out an object literal with a field foo.the-field, but when I try console.log(foo.the-field) I'm told that it's not proper formatting for a JavaScript variable. What gives?

1 Answer 1

6

You need to use the bracket notation instead of dot notation as the member operator here

foo["the-field"]

From Docs

If you are using dot notation then

property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

Sign up to request clarification or add additional context in comments.

1 Comment

Formatting tip: the backticks go inside the brackets :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.