What’s the best practice for embedding arbitrary JSON in the DOM?

Sometimes, we want to embed arbitrary JSON in the DOM.

In this article, we’ll look at what’s the best practice for embedding arbitrary JSON in the DOM.

What’s the best practice for embedding arbitrary JSON in the DOM?

The best practice for embedding arbitrary JSON in the DOM is to put the JSON in a data element.

For instance, we write:

<data class="json-data" value='
  {
    "unicorns": "awesome",
    "abc": [1, 2, 3],
    "careful": "to escape ' quotes"
  }
'></data>

to put or JSON data in a data element’s value attribute.

Then we write:

const jsonData = document.querySelector('.json-data');
const data = JSON.parse(jsonData.value);

console.log(data)

to select the data element with document.querySelector.

And then we call JSON.parse to parse the value attribute of the of data element.

Therefore, data is:

{unicorns: 'awesome', abc: Array(3), careful: "to escape ' quotes"}

Conclusion

The best practice for embedding arbitrary JSON in the DOM is to put the JSON in a data element.