我试图以JSON形式创建对象数组,而不是将其解析回对象。下面是一个工作示例:
var personString = '{"name": "matt","age": 24,"faceFeatures":{"eyes": "green","nose": "medium"},
"hats":["Jays", "TO6", "BassPro"]}'
var person = JSON.parse(personString)
console.log(person)
此代码没有问题。但是,当我尝试清理代码并对其进行多行格式化时,我的代码将失败,这是一个示例:
var personString = '{
"name": "matt",
"age": 24,
"faceFeatures":{"eyes": "green","nose": "medium"},
"hats":["Jays", "TO6", "BassPro"]
}'
我使用了JSON验证器,它说这段代码仍然有效,但是,我的文本编辑器(崇高的)不断给我粉红色的线条,说我有一个封闭的字符串,这对我来说没有意义。因为它和上面的代码完全一样!
当然,我更喜欢此格式的第二个版本,因为它更清晰易读,在使用对象数组时将需要它。非常感谢您的帮助!
答案 0 :(得分:2)
您无需创建这样的多行字符串,而需要添加\
或使用模板文字
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"] \
}'