Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to add JSON on HTML data attribute?

Since HTML data attribute allows adding any custom data, I wonder if it is a good idea to include a set of JSON list as a data attribute? Then, the corresponding JSON can be easily accessed by JavaScript events with getAttribute("data-x").

In fact, my question is that: Is it standard, efficient, and reasonable to add a large set of data to an HTML attribute?

For example

<div data-x="A LARGE SET OF JSON DATA" id="x"> 

Or a large set of JSON data must be stored within <script> tag, and an HTML attribute is not a right place for a large set of data, even for data attribute.

like image 237
Googlebot Avatar asked Apr 05 '13 16:04

Googlebot


People also ask

Can you use JSON in HTML?

JSON can very easily be translated into JavaScript. JavaScript can be used to make HTML in your web pages.

What are data attributes good for HTML?

HTML data-* AttributeThe data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

What are JSON attributes?

JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).

How add data attribute in HTML?

Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.


2 Answers

Instead of storing everything in the data attribute you could use an identifier to access the data.

So for example you could do this :

var myBigJsonObj = {                        data1 : { //lots of data},                        data2 : { //lots of data}                                        }; 

and then you had some html like so :

<div data-dataId="data1" id="x"> 

You can use jquery to get the data now like so :

var dataId = $('#x').attr('data-dataId');  var myData = myBigJsonObj[dataId]; 

This is the best approach imho.

like image 61
BentOnCoding Avatar answered Sep 18 '22 19:09

BentOnCoding


Say you want to save the object var dataObj = { foo: 'something', bar: 'something else' }; to an html data attribute.

Consider first stringifying the object such that we have var stringifiedDataObj = JSON.stringify(dataObj);

Then you can use jQuery to set the stringifiedDataObj as the data attribute e.g. with the jQuery.data() API

like image 26
Athman Avatar answered Sep 21 '22 19:09

Athman