- Best way to store JSON in an HTML attribute?
- 10 Answers 10
- Passing JSON as an html attribute
- 1 Answer 1
- How to Store JSON Array in HTML Attribute and Get it
- EXPLORE THIS ARTICLE TABLE OF CONTENTS
- BONUS Source Code Download
- Download Guideline
- SECTION 1 JSON in Html Attribute
- Embed JSON in HTML OPTION Tag
- Tabular Data in JSON
- CSS Layout
- SECTION 2 JSON From Html Attribute
- Parse JSON into Javascript Object
- Toggle Rows in Table
- FINAL Conclusion
- Learning Tips
- Suggested Reading
- TRY IT Quick Experience
- Try It Yourself
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.
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.
.
Once clicking on element, Javascript embed.js will read JSON data from the selected tag, and display them in element in the form of tabular data.
Tabular Data in JSON
array(["ID", "NAME", "AGE"]), "Female"=>array( ["F01", "Terisa", 23], ["F02", "Lisa", 28]), "Male"=>array( ["M01", "Matt", 30], ["M02", "John", 24]) ); $products=array( "Title"=>array(["PRODUCT", "COLOR", "PRICE", "STOCK"]), "Electronic"=>array( ["iPad", "black", 400, 5], ["Camera", "gray", 180, 3]), "Cloth"=>array( ["T-Shirt", "yellow", 20, 10], ["Coat", "navy", 35, 7]) ); $datalist=array("members"=>$members, "products"=>$products); ?> .
Even though these testing data $members and $products have the multiple-level structure, HTML attribute can keep them well. The two complex tabular data can be integrated into a single array $datalist .
Why we design the example by this way is to help you deeply understand that a HTML attribute contains not only a simple string, but also a complex JSON array.
CSS Layout
body select div table, table tr, table tr th, table tr td table table tr th table tr.bar table tr.bar:hover table tr.bar td table tr td.item @media only screen and (max-width: 720px) < div, table >
CSS file embed.css configures both select for drop-down list and div for tabular data display. Inside div element, table element displays complex JSON data as designed. Considering RWD(Responsive Web Design), @media defines how mobile devices present in proper resolution.
SECTION 2
JSON From Html Attribute
Let us discuss how to display JSON data from HTML attributes. With help of Javascript, parse it first, and then insert them into Table element. As the example data is classified as levels, in Table element, we add an extra tip here about how to toggle partial rows to be hide and show.
Parse JSON into Javascript Object
The PHP scripts define two tabular data. When the select list is dropped down, $(«select#datatype option:selected») will get a selected type attribute, which determines JSON members or products to be retrieved from JSON array.
After that, JSON.parse() parses and retrieves a set of JSON data from HTML attribute value. This data has multiple levels with a special structure and kinds of HTML attributes. Iteratively, you should organize it to fit the format of HTML table element for display.
var magic = < sel : function () < var type = $("select#datatype option:selected").attr("type"); htm = ""; var data = JSON.parse($("select#datatype option:selected").attr("value")); for(typename in data) < if (typename == "Title") < htm += ""; cnt = data[typename][0].length; for (i = 0; i < cnt; i++) < htm += "" + data[typename][0][i] + " "; > htm += " "; > else < htm += ""; for (i = 0; i "; > htm += "" + typename + " "; htm += " "; for(id in data[typename]) < htm += ""; for (i = 0; i < data[typename][id].length; i++) < htm += "" + data[typename][id][i] + " "; > htm += " "; > > > htm += "
"; $("div#display").html(htm); >, .
From Javascript scripts as above, it is difficult to figure out what the resulting HTML codes are like. Referring to a tip Chrome F12 Inspect will help you to check HTML attributes in runtime. The HTML table element will display complex JSON data of members or products.
To clarify, in the beginning, both two tabular data will be embedded in separated HTML attributes value. When option tag is selected, table element just display one of them at a time.
You may notice that the element contains onclick = ‘magic.toggle(this)’ . It is another topic, and will be discussed in next paragraph.
Toggle Rows in Table
The above shows Products include groups of Electric and Cloth. On clicking the green bar, some rows disappear. If clicking again, they appear. This is toggle feature of hiding or showing some specific rows.
FINAL
Conclusion
Beside the principle of JSON in HTML attributes, toggling rows to be hidden and shown is a nice tip in programming. It is worth learning how to leverage this tip in your programming.
Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!
Learning Tips
Let’s suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.
In Google Chrome, there are two ways to inspect a web page using the browser’s built-in Chrome DevTools:
- Right-click an element on the page or in a blank area, then select Inspect.
- Go to the Chrome menu, then select More Tools > Developer Tools.
Suggested Reading
TRY IT
Quick Experience
That’s all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.
Try It Yourself
Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.