JSON requires double quotes for strings

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the data category.

Last Updated: 2021-05-15

This code failed to parse JSON data correctly:

const data = [
  {
    'id': 102,
    'exam_year': 2016,
    'name': 'Competition.pdf',
    'url': 'example.com/competition.pdf',
    'filetype': 'pdf',
    'page_count': 23
  }
]

const html = `<div data-best-notes-file-candidates="${JSON.stringify(data)}"`

The issue was that the JSON format always double quotes strings (even if I create the original JS data with single quotes before transforming it).

These double quotes clash with the double quotes I use to surround the JSON string in my div on the final line, causing failure.

Therefore the solution is to use backtick quotes when building up my string:

const html = `<div data-best-notes-file-candidates='${JSON.stringify(data)}'`

Why not single quotes? Because of the risk of unescaped apostrophes in the data.