suk
suk

Reputation: 25

jquery data attribute not parsing json string

I am saving array of javascript objects in the html data attribute using JSON.stringify(). When I try to retrieve the data using jquery .data() function, I do not get deserialized array of javascript objects back, but gives me plain json string. I read, jquery .data() function deserializes Json string as quoted in documentation

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string

I think, mine is a valid json string, because, if I try $.parseJSON on that, it gives me back array of javascript objects.

Please help!

Upvotes: 0

Views: 1389

Answers (1)

ffflabs
ffflabs

Reputation: 17481

You don't need to stringify objects to store them using jQuery.data(). Just store the object like so:

var myobject = { "name":"john", "age":30};

jQuery('#dataholder').data('theobject',myobject);

console.log(jQuery('#dataholder').data('theobject'));

console.log(jQuery('#data_attribute_method').data('theobject'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="dataholder"></div>

<div id="data_attribute_method" data-theobject='{ "name":"jim", "age":31}'></div>

jQuery will parse (as objects) hard coded data attributes at rendering time, but any data attribute you set as string afterwards, will be stored as text no matter if wrapped in curly braces or not.

Upvotes: 2

Related Questions