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
What if the JSON contains special characters? e.g. {foo: ''}
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:
$data = array(
'1' => 'test',
'foo' => ''
);
$json = json_encode($data);
?>
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);
});