Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to store JSON in an HTML attribute?
    primarykey
    data
    text
    <p>I need to put a JSON object into an attribute on an HTML element.</p> <ol> <li><p><strong><s>The HTML does not have to validate.</s></strong></p> <p><em>Answered by Quentin: <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes" rel="noreferrer">Store the JSON in a <code>data-*</code> attribute</a>, which is valid HTML5.</em></p></li> <li><p><strong>The JSON object could be any size - i.e. huge</strong></p> <p><em>Answered by Maiku Mori: <a href="https://stackoverflow.com/questions/2752457/max-length-of-an-html-attribute-value">The limit for an HTML attribute is potentially 65536 characters</a>.</em></p></li> <li><p><strong>What if the JSON contains special characters? e.g.</strong> <code>{foo: '&lt;"bar/&gt;'}</code></p> <p><em>Answered by Quentin: Encode the JSON string before putting it into the attribute, as per the usual conventions. <a href="http://php.net/htmlentities" rel="noreferrer">For PHP, use the</em> <code>htmlentities()</code> <em>function</a>.</em></p></li> </ol> <hr> <p><strong>EDIT - Example solution using PHP and jQuery</strong></p> <p>Writing the JSON into the HTML attribute:</p> <pre><code>&lt;?php $data = array( '1' =&gt; 'test', 'foo' =&gt; '&lt;"bar/&gt;' ); $json = json_encode($data); ?&gt; &lt;a href="#" data-json="&lt;?php echo htmlentities($json, ENT_QUOTES, 'UTF-8'); ?&gt;"&gt;CLICK ME&lt;/a&gt; </code></pre> <p>Retrieving the JSON using jQuery:</p> <pre><code>$('a').click(function() { // Read the contents of the attribute (returns a string) var data = $(this).data('json'); // Parse the string back into a proper JSON object var json = $.parseJSON($(this).data('json')); // Object now available console.log(json.foo); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload