Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - Best way to store JSON in an HTML attribute?

I need to put a JSON object into an attribute on an HTML element.

  1. The HTML does not have to validate.

    Answered by Quentin: Store the JSON in a data-* attribute, which is valid HTML5.

  2. The JSON object could be any size - i.e. huge

    Answered by Maiku Mori: The limit for an HTML attribute is potentially 65536 characters.

  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The HTML does not have to validate.

Why not? Validation is really easy QA that catches lots of mistakes. Use an HTML 5 data-* attribute.

The JSON object could be any size (i.e. huge).

I've not seen any documentation on browser limits to attribute sizes.

If you do run into them, then store the data in a <script>. Define an object and map element ids to property names in that object.

What if the JSON contains special characters? (e.g. {test: '<"myString/>'})

Just follow the normal rules for including untrusted data in attribute values. Use &amp; and &quot; (if you’re wrapping the attribute value in double quotes) or &#x27; (if you’re wrapping the attribute value in single quotes).

Note, however, that that is not JSON (which requires that property names be strings and strings be delimited only with double quotes).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...