Basically I have a JSON file and whenever I take it to my js application and print it to the console it never print a new line I have no Idea why
my JSON file:
[
{
"id": "71046",
"question": "What is a cpu?",
"answer": "Brain of the computer, it has all the circuity needed to proccess input, store data and output results.",
"options": [""]
},
{
"id": "63888",
"question": "What can the proccessor perform?",
"answer": "1) Basic arithmetic 2) Logic Control 3) Input/Output",
"options": []
},
{
"id": "5418",
"question": "CPU principle components:",
"answer": "1) ALU (Arithmetic Logic Unit)\n 2) Processor Register\\n 3) Control Unit",
"options": []
}
]
I tried many solution to parse print and others and didn't work which is weird
I went through this link in stackoverflow and didn't find solution:
CodePudding user response:
That's probably because you don't "print JSON", but "print a JS object"
Basically, what you would get if the console would be in a browser and not in nodejs is
To print JSON as JSON you must convert it back to text with JSON.stringify
JSON.stringify(
{
"id": "71046",
"question": "What is a cpu?",
"answer": "Brain of the computer, it has all the circuity needed to proccess input, store data and output results.",
"options": [""]
}
),
/*replacer(advanced)*/
undefined,
/*indent as <string> of spaces <number>*/
2
)
CodePudding user response:
Each valid JSON is a valid JS
What you are trying to get is
let j = "multiline
string"
which is obviously invalid in JS or JSON
This is caused by JSON stringifying strings.
Stringified strings can't contain newline, JSON allows newlines
For example:
const str = `
- multiline
- string
`
const json = JSON.stringify(str)
// expected = '" \n- multiline \n- string \n"' - no newli
const expected = '"\\n- multiline\\n- string\\n"'
console.log(json == expected)
console.log(json.includes('\n')) // false, does not contain newlines
try {
console.log(JSON.parse('"asi\nzxc"'))
} catch(err) {
/**
* Unexpected token
* in JSON at position 4
*/
console.log(err)
}
/**
* {
* "json": "\"\\n- multiline\\n- string\\n\""
* }
*/
console.log({json})
JSON.stringify(str)