Is it possible to store a JSON object directly into the DOM somehow?

dom, javascript, json

Solution

Data attributes have to be strings, you can't store objects in them directly. So don't parse the JSON string, just store the JSON string directly in the dataset attribute.

If you use jQuery, its `.data()` method will take an object, and it will automatically stringify it as needed.

If the elements you want to associate the object with all have IDs, another option is to use a global object as a table, keyed off the element's ID.

jsonTable[id] = jsonObject;

Problem

If one has the output of a JSON.parse readily at hand, is there some legitimate way of storing that object in the DOM as a single entity? i.e. jsonObject = JSON.parse(something); I'd like to consider storing the jsonObject in the DOM as a (child || textNode || ???) of some element and later retrieving it so that immediately after retrieval I could access its contents via the usual: jsonObject.keyName I want to avoid adding dozens of dataset attributes and later being forced to extract them one at a time. That's too much work and seems too inefficient if you have dozens of key:value pairs.

Original source