String1是我通过here验证的有效JSON字符串。但是,如果用引号引起来并将其放在JavaScript文件中,则会出现错误-未终止的字符串常量
let json_string = "insert string1 below here";
答案 0 :(得分:1)
通常对于这种方法,您需要导出一些常量
export const JSON_STRING = // .... stuff
对于多行字符串,您想尝试在JS中使用新的模板字符串。只需在字符串前后添加反引号
export const JSON_STRING = `
{
"foo": bar
}
`
最后,您可以考虑不将其存储为字符串。只需将其编写为普通的JSON,然后在何时/如果需要对其进行字符串化,请调用JSON.stringify
export const JSON_DATA = { ... }
// some other place
let data_as_string = JSON.stringify(JSON_DATA);
答案 1 :(得分:0)
使用反引号(`)将字符串括起来,而不是常规的单引号/双引号:
let json_string = `
[{
"link": "https://www.hsph.harvard.edu/nutritionsource/healthy-eating-plate/",
"image": "https://i.imgur.com/xoqLsJq.png",
"title": "Harvard has a nutrition plate and food pyramid",
"summary": "Harvard nutrition experts created these tools to make healthy eating easy.",
"tag": "Diet",
"domain": "hsph.harvard.edu",
"date": "Jan 01, 2018",
"upvotes": "100"
}, {
"link": "https://www.weforum.org/agenda/2017/06/changing-the-way-america-eats-moves-and-connects-one-town-at-a-time/",
"image": "https://i.imgur.com/wSpfyPZ.jpg",
"title": "9 lessons on longevity from 5 blue zones",
"summary": "In certain parts of the world people live abnormally long with good health. They are known as the blue zones.",
"tag": "Health",
"domain": "weforum.org",
"date": "June, 2017"
}]
`
当用反引号括起来的字符串时,它将成为“模板字符串”或“模板文字”。这里有更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
答案 2 :(得分:0)
使用带反引号(`)的字符串文字。引号和/或换行符不会出现此问题。
答案 3 :(得分:0)
在JS中,要制作多行字符串,必须在每行末尾添加“ \”,或者使用es6中引入的新“`”。带有反勾号“`”,您无需在每行末尾添加“ \”。
还有两种使用引号声明字符串的方法。 “ vs'。
在您的示例中,您到处都有相同的引号。而是使用单引号表示完整字符串,并使用双引号声明json键。
答案 4 :(得分:0)
为简洁起见,请按此处所述使用ES6模板文字:
http://es6-features.org/#StringInterpolation
它将解决换行问题,该问题会提前终止您的字符串。
这涉及这样使用反引号(`):
let json_string = `
[{
...
}]`;
答案 5 :(得分:-2)
您的代码中的问题是换行符。这会导致字符串语法的中断。
Backticks(`)是您解决问题的方法。您可以使用它们制作多行字符串。
在此处查看示例
var string = `string text line 1
string text line 2`