0

It is possible change form key in JSON from key in double quotes to key without quotes?

from

let a = {
   "key1": "value1",
   "key2": "value2",
   "key3": "value3"
}

to

let b = {
    key1: "value1",
    key2: "value2",
    key3: "value3"
}
0

1 Answer 1

1

This is a valid JavaScript Object, but it is not valid JSON:

let b = {
    key1: "value1",
    key2: "value2",
    key3: "value3"
}

If you are writing JavaScript, you can do it like that without issues.

You can also use single quotes or grave accents. These are both valid:

let b = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
}

and

let b = {
    key1: `value1`,
    key2: `value2`,
    key3: `value3`
}

In some situations, you need to include the single, double, or grave accents. For example, when your key starts with a number or has spaces in it:

You would need them for this:

let obj = {
  '0key': 'value'
}

and this:

let obj = {
  'john smith': 'value'
}

Here is some supplementary reading:

Consider dot notation while you are asking if it is valid.

b.key1 is valid dot notation, but b.0 is not, and neither is b.john smith.

The other notation is bracket notation which allows you to refer to keys that do not work with dot notation.

b['key1'] is valid bracket notation, and so is b['0'] and b['john smith'].

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

3 Comments

"The only times" --- those are far from the exhaustive list of the cases when you need to enclose it in the quotes.
Yes I should be more clear. I will see if I can find a better list, perhaps from MDN.
The easiest would be: "If it's not a valid identifier - it should be put in quotes"

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.