Search code examples
javascriptnode.jsjsonunicodeemoji

'Unexpected token in JSON' when trying to save emojis to a file and the parse the file back to json


    const message = { message: 'Thanks again 👸💋' };

    const res1 = await fs.writeFileSync('test123.json', JSON.stringify(message));
    const fileBuffer = await fs.readFileSync('test123.json');

    const json = JSON.parse(fileBuffer.asciiSlice()); // can't parse JSON
  

Gives me:

Uncaught SyntaxError SyntaxError: Unexpected token  in JSON at position 26
    at eval (repl:1:6)

How can I save this json with emojis to a file so that I can parse it back to json?


Solution

  • I added { encoding: 'utf8' } when reading the file. Now it returns as a string with the correct emojis.

    const res1 = await fs.writeFileSync('test123.json', JSON.stringify(message));
    const string = await fs.readFileSync('test123.json', { encoding: 'utf8' });
    const json = JSON.parse(string);