Although I saw the suggested methods used and working, I think setting the value of the hidden field using JSON.stringify only interrupts the HTML ...
Here I will explain what I mean:
<input type="hidden" value="{"name":"John"}">
As you can see the first double quote after the open chain can be interpreted by some browsers as:
<input type="hidden" value="{" rubbish >
So, for a better approach to this, I would suggest using the encodeURIComponent function. Together with JSON.stringify, we have something like the following:
> encodeURIComponent(JSON.stringify({"name":"John"})) > "%7B%22name%22%3A%22John%22%7D"
Now this value can be safely stored in a hidden form of input, for example:
<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">
or (even better) using the data attribute of an HTML element controlled by a script that will consume data, for example:
<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>
Now, to read the data back, we can do something like:
> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json"))) > console.log(data) > Object {name: "John"}
rodu Aug 26 '13 at 11:42 on 2013-08-26 11:42
source share