Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store JSON object in data attribute in HTML jQuery

Tags:

json

html

jquery

Actually, your last example:

<div data-foobar='{"foo":"bar"}'></div>

seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).

The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don't see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.

(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).


instead of embedding it in the text just use $('#myElement').data('key',jsonObject);

it won't actually be stored in the html, but if you're using jquery.data, all that is abstracted anyway.

To get the JSON back don't parse it, just call:

var getBackMyJSON = $('#myElement').data('key');

If you are getting [Object Object] instead of direct JSON, just access your JSON by the data key:

var getBackMyJSON = $('#myElement').data('key').key;

This is how it worked for me.

Object

var my_object ={"Super Hero":["Iron Man", "Super Man"]};

Set

Encode the stringified object with encodeURIComponent() and set as attribute:

var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);

Get

To get the value as an object, parse the decoded, with decodeURIComponent(), attribute value:

var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));

A lot of problems with storing serialized data can be solved by converting the serialized string to base64.

A base64 string can be accepted just about anywhere with no fuss.

Take a look at:

  • btoa()

The WindowOrWorkerGlobalScope.btoa() method creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

  • atob()

The WindowOrWorkerGlobalScope.atob() function decodes a string of data which has been encoded using base-64 encoding.

Convert to/from as needed.


For me it work like that, as I need to store it in template...

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

Combine the use of window.btoa and window.atob together with JSON.stringify and JSON.parse.

- This works for strings containing single quotes

Encoding the data:

var encodedObject = window.btoa(JSON.stringify(dataObject));

Decoding the data:

var dataObject = JSON.parse(window.atob(encodedObject));

Here is an example of how the data is constructed and decoded later with the click event.

Construct the html and encode the data:

var encodedObject = window.btoa(JSON.stringify(dataObject));

"<td>" + "<a class='eventClass' href='#' data-topic='" + encodedObject + "'>" 
+ "Edit</a></td>"

Decode the data in the click event handler:

$("#someElementID").on('click', 'eventClass', function(e) {
            event.preventDefault();
            var encodedObject = e.target.attributes["data-topic"].value;
            var dataObject = JSON.parse(window.atob(encodedObject));

            // use the dataObject["keyName"] 
}

There's a better way of storing JSON in the HTML:

HTML

<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>

JavaScript

JSON.parse(document.getElementById('some-data').textContent);