1

I was trying to create an array of objects is JSON form, and than parsing them back into an object. Below is a working example:

var personString = '{"name": "matt","age": 24,"faceFeatures":{"eyes": "green","nose": "medium"},
"hats":["Jays", "TO6", "BassPro"]}'

var person = JSON.parse(personString)
console.log(person)

This code works no problem. However, when I try to clean up my code and format it on multiple lines, my code fails, here is an example:

var personString = '{
    "name": "matt",
    "age": 24,
    "faceFeatures":{"eyes": "green","nose": "medium"},
    "hats":["Jays", "TO6", "BassPro"]
}'

I used the JSON validator, and it says this block of code is still valid however, my text editor, which is sublime, keeps giving me pink lines saying I have an enclosed string, which doesn't make sense to me. As it is the exact same code as above!

Of course I would prefer the second formatted version of this, as it is much cleaner to read and will be needed when I use an array of objects. Any help is greatly appreciated, thanks!

1
  • use ` not ' this is for multiline strings. Commented Aug 6, 2018 at 16:16

1 Answer 1

5

You don't create multiline string like this you need to add \ or use template literal

var personString = `{
    "name": "matt",
    "age": 24,
    "faceFeatures":{"eyes": "green","nose": "medium"},
    "hats":["Jays", "TO6", "BassPro"]
}`
// OR
var personString = '{ \
    "name": "matt",   \
    "age": 24,        \
    "faceFeatures":{"eyes": "green","nose": "medium"}, \
    "hats":["Jays", "TO6", "BassPro"] \
}'
Sign up to request clarification or add additional context in comments.

Comments

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.