How to Store JSON Array in HTML Attribute and Get It

Best way to store JSON in an HTML attribute?

You should probable explain why and ask for different solution since I’m quite sure this isn’t the best. You can prob use data-something attributes but I’m not sure if they can hold «huge» amount of text. As for special chars you can just encode (escape() and unescape()) the text.

Btw, if your attribute is named data-json you should use $(this).data(‘json’) , the jQuery has you covered on that part.

Just a note, naming the data-suffix to json is not required. If you put valid json in any data-custom_attribute it will work fine with jQuery.

10 Answers 10

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 . Define an object and map element id s to property names in that object.

Читайте также:  Заголовок страницы

Just follow the normal rules for including untrusted data in attribute values. Use & and " (if you’re wrapping the attribute value in double quotes) or ' (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).

So you’re saying I should do htmlentities($json) before I put it into the HTML attribute? And then how do I decode that when I want to read it in jQuery? And then how do I write it back in using jQuery in the same way that it was in PHP?

So you’re saying I should do html_encode($json) before I put it into the HTML attribute? — if you’re using PHP, then that would work. And then how do I decode that when I want to read it in jQuery? — Decode from the attribute? The browser will do that when it parses the HTML into a DOM. And then how do I write it back in using jQuery in the same way that it was in PHP? — You’re setting attributes of DOM nodes, not generating raw HTML, the browser will take care of it.

At the minute I have an issue where my browser isn’t decoding it currently on Google Chrome, and when I go to parse JSON all the HTML entities are the there and fails.

If you put it in a script tag, you have to escape it differently because of the special handling of script tags. e.g. a value with in it would end the script tag.

Another way you can do it – is put json data inside tag, but not with type=»text/javascript» , but with type=»text/bootstrap» or type=»text/json» type, to avoid javascript execution.

Then, in some place of your program, you can ask for it in this way:

function getData(key) < try < return JSON.parse($('script[type="text/json"]#' + key).text()); >catch (err) < // if we have not valid json or dont have it return null; >> 

On server side, you can do something like this (this example with php and twig):

For JSON use the script type «application/json». Also it is nice to have the top level as an object in the long run.

This doesn’t directly answer the op’s question but it was still very helpful to me. The data I’m storing applies to the page as a whole and not to any specific element, so an element attribute doesn’t really work (unless I put it like on the body element, which just seems kinda lame to me especially since my data can be big). Storing it in a

This answer contains false / dangerous information! Changing script type doesn’t modify the detection of tags. Just try: "

Depending on where you put it,

  • In a as you asked, you need to ensure that the JSON does not contain HTML specials that could start a tag, HTML comment, embedded doctype, etc. You need to escape at least < , and & in such a way that the original character does not appear in the escaped sequence.
  • In or escaping text boundary: .
  • In event handlers you need to ensure that the JSON preserves its meaning even if it has things that look like HTML entities and does not break attribute boundaries ( » or ‘ ).

For the first two cases (and for old JSON parsers) you should encode U+2028 and U+2029 since those are newline characters in JavaScript even though they are allowed in strings unencoded in JSON.

For correctness, you need to escape \ and JSON quote characters and it’s never a bad idea to always encode NUL.

If the HTML might be served without a content encoding, you should encode + to prevent UTF-7 attacks.

In any case, the following escaping table will work:

  • NUL -> \u0000
  • CR -> \n or \u000a
  • LF -> \r or \u000d
  • » -> \u0022
  • & -> \u0026
  • ‘ -> \u0027
  • + -> \u002b
  • / -> \/ or \u002f
  • < ->\u003c
  • > -> \u003e
  • \ -> \\ or \u005c
  • U+2028 -> \u2028
  • U+2029 -> \u2029

So the JSON string value for the text Hello, ! with a newline at the end would be «Hello, \u003cWorld\u003e!\r\n» .

Источник

Passing JSON as an html attribute

I am experiencing an issue where I am in need of passing a JSON as an HTML attribute. I have the JSON string:

  • Use a giant regular expression to escape any offending instances in the json file. This for two primary reasons, the first being that it was slow, but more importantly it is a «dumb» solution and often makes mistakes causing additional errors, and data corruption.
  • Convert the entire json structure into base64/hex; pass this encoded structure to file-json ; and then in the javascript when it is read, convert it from base64 back into a json string; and finally continue processing. This so far is the best solution that I have come up with as it is the only one that cannot cause data corruption. However it is both slow and consists of a large number of moving parts leading to issues in maintainability and expandability.

Why not just format it properly before you put it there? Just do JSON.stringify(JSON.parse(data)) and you’ll get a normalised representation

«Which I am passing to a html attribute». Is this being populated in some server side code? If so should be easy to escape there

1 Answer 1

Your json looks like valid json, so a simple JSON.stringify should do the job

var json = var stringified = JSON.stringify(json); // or whatever element identifier you have document.getElementById('foo').setAttribute('file-json', stringified) 

if not and its really a string, simply add JSON.parse()

var stringified = JSON.stringify(JSON.parse(json)); 

Источник

How to Store JSON Array in HTML Attribute and Get it

You can store JSON object or JSON array into an attribute on an HTML element, just as you treat them as strings. This article teach you how to embed JSON data in HTML, and moreover, retrieve it from HTML attributes.

Along with this major topic, an extra tip about toggling to hide or show some rows in HTML Table elements can be found here, too.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 7 minutes

EXPLORE THIS ARTICLE
TABLE OF CONTENTS

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.

SECTION 1
JSON in Html Attribute

In general, AJAX is used to request data on demand. But now we present an alternative approach which gets all data at loading time. Then we store JSON object or array in HTML attribute.

Embed JSON in HTML OPTION Tag

You can not only put a string into HTML attribute, for instance, , but also store a JSON object or array in HTML.

Store JSON in HTML Attribute

See below, the function json_encode($data) converts data into JSON array. Then we embed the JSON array into HTML attribute value , which is truely complex tabular data, instead of a simple string.

.        element is used to create a drop-down list, while the