Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting HTML in JSON

Tags:

json

html

php

As per title, is it considered a good practice to put HTML in JSON? The reason I need to do this is because I would like to have a custom dropdown where the list is coming from the user input, and the json looks like so:

{ listTitle: 'Tasks', listHtml: '<ul><li></li>...</ul>' }

and I have the foreach as following (keep in mind this is a stripped down version of my code, validation is in place, but for the sake of this question I took them out)

$list = /** Code to grab 'Tasks' list and its title from mysql **/;
$title = 'Tasks';
$listHtml = '';
foreach($list as $content) { $listHtml .= '<li>' . htmlspecialchars($content, ENT_QUOTES, 'UTF-8') . '</li>'; }

exit(json_encode(array(
   'title' => $title, 'listHtml' => '<ul>' . $listHtml . '</ul>'
)));

My worry is that there might be some special characters that might break the JSON String. Please help.

like image 685
Andreas Wong Avatar asked Feb 29 '12 02:02

Andreas Wong


People also ask

Can we add HTML to JSON file?

You can add HTML to some elements though. I see <a>, <b> and <strong> html tags in en. json file but if you put these to other variables, they just print like text.

How escape HTML tag JSON?

However, if your data contains HTML, there are certain things that you need to do to keep the browser happy when using your JSON data within Javascript. Escape the forward slash in HTML end tags. <div>Hello World!


1 Answers

You wouldn't be the first to do it, and certainly not the last.

To really answer the question, assuming you're following the protocol/standard and not breaking it (including quotes in the string without escaping them, for instance) you should be fine. json_encode does a great job at all this, but as @Kolink mentioned make sure you encode it to UTF8 first otherwise stray Unicode characters will occasionally break it resulting in empty output.

Beyond that, it's programmer preference to use it. Some avoid it and keep the UI work on the page, others have the server generate the UI and let JavaScript just dump it--either way it's your call, and perfectly acceptable.

like image 63
Brad Christie Avatar answered Sep 28 '22 07:09

Brad Christie