Categories
JavaScript Answers

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

Spread the love

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 &#39; 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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *