如何在JavaScript文件中保存JSON字符串?

如何在JavaScript文件中保存JSON字符串?,javascript,json,Javascript,Json,下面的String1是经过验证的有效JSON字符串。然而,如果我在它的周围加上引号,并将它放在JavaScript文件中,我会得到一个错误-未终止的字符串常量 使用反勾号(`)将字符串括起来,而不是使用常规的单引号/双引号: let json_string = ` [{ "link": "https://www.hsph.harvard.edu/nutritionsource/healthy-eating-plate/", "image": "https://i.imgur.com/xoqLsJ

下面的String1是经过验证的有效JSON字符串。然而,如果我在它的周围加上引号,并将它放在JavaScript文件中,我会得到一个错误-未终止的字符串常量


使用反勾号(`)将字符串括起来,而不是使用常规的单引号/双引号:

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"
}]
`
当用反勾号括住字符串时,它将成为“模板字符串”或“模板文字”。更多信息请点击此处:


使用带反勾(`)的字符串文字。引号和/或换行符不会有这个问题

通常对于这种方法,您需要导出一些常量

export const JSON_STRING = // .... stuff
对于多行字符串,您可能希望尝试在JS中使用新的模板字符串。只需在字符串前后添加反勾号

export const JSON_STRING = `
  {
    "foo": bar
  }
`
最后,您可能会考虑不将其存储为字符串。只需将其编写为普通JSON,然后在需要对其进行字符串化时调用


代码中的问题是换行符。它会导致字符串的语法中断

(`)是您问题的解决方案。您可以使用它们生成多行字符串

请参见此处的示例:

var string = `string text line 1
string text line 2`

在JS中,要生成多行字符串,必须在每行末尾加上“\”或使用es6中引入的新“`”。如果在后面打“`”,则不需要在每行末尾都加“\”

还有两种使用引号声明字符串的方法。“对”


在您的示例中,到处都有相同的引号。相反,使用单引号表示完整字符串,双引号表示json键。

json=JavaScript对象表示法,它是JavaScript对象的字符串表示法。编写JavaScript时,您需要使用大括号和键:property pairsPossi你能解释为什么这样做吗?为什么我的字符串无效?换行符导致语法中断。你能解释为什么这样做吗?为什么我的字符串无效?它不起作用的原因是,常规javascript字符串必须在下一个换行符之前终止。对于反勾号,情况并非如此。噢…换行符。谢谢!答案仅包含指向外部站点的链接(即使是官方文档)应避免。请添加一些解释/代码以改进您的答案。
export const JSON_DATA = { ... }

// some other place
let data_as_string = JSON.stringify(JSON_DATA);
var string = `string text line 1
string text line 2`