I need to put a JSON object into an attribute on an HTML element.
The HTML does not have to validate.
Answered by Quentin: Store the JSON in a
data-*
attribute, which is valid HTML5.The JSON object could be any size - i.e. huge
Answered by Maiku Mori: The limit for an HTML attribute is potentially 65536 characters.
What if the JSON contains special characters? e.g.
{foo: '<"bar/>'}
Answered by Quentin: Encode the JSON string before putting it into the attribute, as per the usual conventions. For PHP, use the
htmlentities()
function.
EDIT - Example solution using PHP and jQuery
Writing the JSON into the HTML attribute:
<?php
$data = array(
'1' => 'test',
'foo' => '<"bar/>'
);
$json = json_encode($data);
?>
<a href="#" data-json="<?php echo htmlentities($json, ENT_QUOTES, 'UTF-8'); ?>">CLICK ME</a>
Retrieving the JSON using jQuery:
$('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);
});
See Question&Answers more detail:os