ibmkhd
ibmkhd

Reputation: 799

JSON.parse file input differ from parsing string literal

Im using nodejs to parse some JSON files and insert them into mongodb,the JSON in these files have invalid JSON characters like \n,\" etc .. The thing that i dont understand is that if i tried to parse like :

console.log(JSON.parse('{"foo":"bar\n"}'))

i get

   undefined:1
  {"foo":"bar

but if i tried to parse the input from the file (The file has the same string {"foo":"bar\n"})like:

new lazy(fs.createReadStream("info.json"))
    .lines
    .forEach(function(line){    
var line = line.toString(); 
        console.log(JSON.parse(line));
    }
);

every thing works fine , i want to know if this fine and its ok to parse the files i have, or i should replace all invalid JSON characters before i parse the files , and why is there a difference between the two.

Thanks

Upvotes: 0

Views: 539

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382170

If you can read "\n" if your text file, then it's not an end of line but the \ character followed by a n.

\n in a JavaScript string literal adds an end of line and they're forbidden in JSON strings.

See json.org :

enter image description here

To put an end of line in a JSON string, you must escape it, which means you must escape the \ in a JavaScript string so that there's "\n" in the string received by JSON.parse :

console.log(JSON.parse('{"foo":"bar\\n"}'))

This would produce an object whose foo property value would contain an end of line :

enter image description here

Upvotes: 3

Related Questions