JSON in HTML Document

So.. you have really understood what JSON is, now we’ll discuss the real-world use of the JSON in HTML Document.


Under certain conditions, we need to put JSON data in the HTML Document.

Usually, there are two situations related this: (1) Submitted the JSON data with other input elements (the JSON data will be placed inside <form> element) (2) Just need a place to put the JSON data for later use.

JSON in HTML Element: Where should be placed?

In the HTML element, the JSON data can be placed within (1) HTML element attribute or (2) inside HTML element.

Putting JSON in HTML element attribute is a bit complicated because JSON uses double quotes (“) for both key and value (for string data type) while HTML element also uses quotes on its attributes, for example:

<input type="hidden" value="{"title":"webdevzoom"}"/>

The above code will cause an error as the open quote of the attribute immediately closed by JSON quote of the first key, to solve that, we need to do some “tricks”. At least, there are three things that we can do:

1. JSON in HTML Element’s Attribute

Putting JSON data in HTML element attribute is the common way to place the JSON data, just like the previous example, but…. is this safe? let’s see…

1.a. Using Single Quote

Usually, the HTML element attribute enclosed using double quotes, but if the attribute’s value is a JSON, then we can’t use double quotes, instead, we use single quotes.

Suppose we create an edit form that contains old data (in JSON) we want to edit as follows:

<?php
$site_options = array('title' => 'Webdevzoom'
			, 'desc' => 'Web developer community for euthiast programmer"'
		);
?>
<form method="post" action="edit_user.php">
	Title : <input type="text" name="title" value="<?=@$_POST['title']?>"/>
	Description : <input type="text" name="description" value="<?=@$_POST['description']?>"/>
	<input type="hidden" name="site_options" value='<?=json_encode($site_options)?>'/>
	<input type="submit" name="submit" value="Sumbit">
</form>

Notice that in the above example, we use single quotes (‘) for the attribute that contains JSON data (line 9). When printed to the browser, that attribute value becomes:

<input type="hidden" name="site_options" value='{"title":"Webdevzoom","desc":"Web developer community for euthiast programmer"}'/>

Using single quotes on HTML attribute is a valid HTML standard, but if the JSON data contains single quotes and doesn’t escaped, then it will cause an error because it will collide with the open quote of the attribute value, for example:

<input type="hidden" name="site_options" value='{"title":"Webdevzoom","desc":"Web developer community for 'euthiast' programmer"}'/>

To solve that, we need to convert the single quote to another character such as hexadecimal, with PHP we can achieve that using the  JSON_HEX_APOS option, for example: json_encode($site_option, JSON_HEX_APOS)

See: JSON With PHP – A Complete Guide

With the HEX character on the single quote, the above JSON string becomes:

<input type="hidden" name="site_options" value='{"title":"Webdevzoom","desc":"Web developer community for \u0027euthiast\u0027 programmer"}'/>

Note: When we parse the JSON string (e.q using json_decode function with PHP), then the hex value will be converted back to single quotes.

JSON in HTML Data Attribute

The above method can also be used when placing the JSON data into other HTML attributes, such as data attribute, this is sometimes used when creating a custom tooltip.

An example:

<a href="http://webdevzoom.com" title="Webdevzoom" class="tooltip" data-tooltip='{"title"="Webdevzoom", "url"="http://webdevzoom.com", "desc"="Web developer community for euthiast programmer"}'>
  Webdevzoom
</a>

1.b. Using Double Quotes

Instead of single quotes, we can still use the double quotes to enclose the attribute value, but… to avoid an error, we need to convert the HTML character into their entity character (HTML Entities).

With PHP, we can achieve that using the htmlentites() function, for example, from the previous example, we change the code to the following:

<?php
$site_options = array('title' => 'Webdevzoom'
			, 'desc' => 'Web developer community for euthiast programmer'
		);
$data = json_encode($site_options);
?>
<form method="post" action="edit_user.php">
	Title : <input type="text" name="title" value="<?=@$_POST['title']?>"/>
	Description : <input type="text" name="description" value="<?=@$_POST['description']?>"/>
	<input type="hidden" name="site_options" value="<?=htmlentities($data)?>"/>
	<input type="submit" name="submit" value="Submit">
</form>

Note: We can use the ENT_QUOTES option to convert both single and double quote, for example: htmlentities($data, ENT_QUOTES).

When printed to a browser, we’ll get the following JSON data:

<input type="hidden" name="site_options" value="{&quot;title&quot;:&quot;Webdevzoom&quot;,&quot;desc&quot;:&quot;Web developer community for \&quot;euthiast\&quot; programmer&quot;}"/>

To restore to its original form, we can use the html_entity_decode() function, if we use the ENT_QUOTES option when using htmlentities(), then we should also use that option on the html_entity_decode().

Note: It is important to note that the above HTML entity functions only available in PHP, if we process the encoded data using javascript, then things become more complicated, so, if possible, avoid this method, use solution number 1.a and 2 instead

2. JSON in HTML Element: Leave As Is

The second method to place JSON data into HTML document is putting the JSON data inside HTML element. Using this method, we can leave the JSON data as is and don’t worry about single or double quotes.

For example, within HTML form, we can place JSON string into <textarea> element, so the data will be submitted along with other input forms:

<form method="post" action="option_edit.php">
	Title : <input type="text" name="title" value="<?=@$_POST['title']?>"/>
	Description : <input type="text" name="description" value="<?=@$_POST['description']?>"/>
	<input type="submit" name="submit" value="Save">
	<textarea style="display:none"><?=json_encode($site_options)?></textarea>
</form>

Note: we add the style="display:none" to hide the textarea from users.

or, if we just need a place to put the JSON data and don’t want to submit it, we can use other elements, such as <span>, <div>, etc…

For Example:

<span id="site-options" style="display:none">{"title":"Webdevzoom","desc":"Web developer community for 'euthiast' programmer","base_url":"http://webdevzoom.com"}</span>

So… compared to the others, this method is more simple and doesn’t worry about errors caused by quotes, I, personally prefer to use this method.

3. JSON in HTML Document: Leave As Is

So now we know that if we just need a place to put JSON in HTML document, we can put it on an attribute of elements or inside the element itself.

In addition to the above methods, there is another alternative that we can use, that is putting JSON data on javascript variables.

For example: here is a script to create a multi-level drop-down from a database data

<?php
$query = mysqli_query($conn, 'SELECT category_id, category_name, parent FROM product_category WHERE parent != 0');

while ($row=mysqli_fetch_array($query)) {
  $data[$row['parent']][] = array('category_id' => $row['category_id'], 'category_name' => $row['category_name']);
}
echo "<script type='text/javascript'>var json=" . json_encode($data, JSON_HEX_QUOT) . "</script>";
echo site_footer(array('js/json-local-static.js'), basename(__DIR__));
?>

When printed on a browser,  the 7th line becomes:

<script type='text/javascript'>var json={"1":[{"category_id":"2","category_name":"Music & Instruments"},{"category_id":"3","category_name":"Hobbies"},{"category_id":"4","category_name":"Computer & Internet"},{"category_id":"5","category_name":"Programming"}]}</script>

Note: on the above examp-le, the json variable contains data that have exact same format with JSON, however, it is not a JSON but a javascript object.

Why?

Because it is not a string (it doesn’t enclosed with quotes), while JSON is a string, so, to use it, we don’t need to parse, just use it as other javascript objects.

Wrap Up

Putting JSON data in an HTML document sometimes tricky, so to make sure everything goes well, we can consider two things as follows:

  1. If we want the JSON data to be submitted, then we can put it within <textarea></textarea> element.
  2. If we just need a place to put the JSON data, then if possible, put it in a Javascript variable, or put it on not-submitable html elements such as: <span> or <div>

Ok, that’s all about JSON in HTML document, have some idea? leave it bellow.

Subscibe Now

Loves articles on webdevzoom.com? join our newsletter to get quality article right to your inbox. Nothing else, just quality stuff!!!

Our Commitment: We respect your privacy, we'll not share your credential to any party

Leave a comment

Like Us

Newsletter

Great information from webdevzoom.com right to your inbox

  1. Understanding JSONP – With Javascript and jQuery Examples

  2. JSON With Javascript and Ajax

  3. JSON From Database – PHP and MySQL

  4. JSON in HTML Document

  5. JSON With PHP – A Complete Guide

  6. Understanding JSON – A Comprehensive Guide

  7. 7 Best Free Online Image Compressor & Optimizer Tools – Compared & Tested

  8. 40+ Modern Free WordPress Themes For Blog in 2017 – Beautiful & Responsive

  9. Understanding Constant in PHP – Updated to PHP 7

  10. Understanding Variable in PHP – All PHP Version