String1, below, is valid JSON string I have as verified here. However if I put quotes around it and put it in a JavaScript file I get an error - unterminated string constant
let json_string = "insert string1 below here";
String1, below, is valid JSON string I have as verified here. However if I put quotes around it and put it in a JavaScript file I get an error - unterminated string constant
let json_string = "insert string1 below here";
Usually for this approach, you would want to export some constant
export const JSON_STRING = // .... stuff
For multiline strings, you would want to try using the new template strings in JS. Just add a backtick before and after the string
export const JSON_STRING = `
{
"foo": bar
}
`
Finally, you might consider not storing it as a string. Just write it as normal JSON and then when/if you need to stringify it call JSON.stringify
export const JSON_DATA = { ... }
// some other place
let data_as_string = JSON.stringify(JSON_DATA);
Use the backtick character (`) to enclose the string, instead of the regular single/double quotes:
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"
}]
`
When you enclose a string with backticks, it becomes a "Template string" or a "template literal". More info here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Use string literal with backticks (`) . You won't have this problem with quotes and/or newlines.
In JS to make multiline string you have to put "\" at end of every line OR use new "`" introduced in es6. With back tick, "`", you don't need to put "\" at the end of every line.
Also there are two ways to declare string using quotation mark. " vs '.
In your example you have same quotation marks all over. Instead use single quotation mark for full string, and double quotation mark to declare json keys.
The problem in your code is the newline character. It causes the break in the syntax of your string.
Backticks (`) are the solution for your problem. You can use them to make to make multi-line strings.
See example here:
var string = `string text line 1
string text line 2`