Is it possible to write an HTML string inside JSON?
Which I want to write like below in my JSON file:
[
{
\"id\": \"services.html\",
You should escape the characters like double quotes in the html string by adding "\"
eg: <h2 class=\"fg-white\">
You could make the identifier a param for a query selector. For PHP and compatible languages use an associative array (in effect an objects) and then json_encode.
$temp=array('#id' =>array('href'=>'services.html')
,'img' =>array('src'=>"img/SolutionInnerbananer.jpg")
,'.html'=>'<h2 class="fg-white">AboutUs</h2><p class="fg-white">...</p>'
);
echo json_encode($temp);
But HTML don't do it for you without some JS.
{"#id":{"href":"services.html"},"img":{"src":"img\/SolutionInnerbananer.jpg"}
,".html":"<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">...<\/p>"}
One way is to replace the double quotes in the HTML with single quotes but using double quotes has become the standard convention for attribute values in HTML.
The better option is to escape the double quotes in json and other characters that need to be escaped.
You can get some more details about escaping here: Where can I find a list of escape characters required for my JSON ajax return type?
4 Things You Must Do When Putting HTML in JSON:
1) Escape quotation marks used around HTML attributes like so
<img src=\"someimage.png\" />
2) Escape the forward slash in HTML end tags.
<div>Hello World!<\/div>.
This is an ancient artifact of an old HTML spec that didn't want HTML parsers to get confused when putting strings in a<SCRIPT>
tag. For some reason, today’s browsers still like it.3) This one was totally bizarre. You should include a space between the tag name and the slash on self-closing tags. I have no idea why this is, but on MOST modern browsers, if you try using javascript to append a
<li>
tag as a child of an unordered list that is formatted like so:<ul/>
, it won't work. It gets added to the DOM after the ul tag. But, if the code looks like this:<ul />
(notice the space before the /), everything works fine. Very strange indeed.4) Be sure to encode any quotation marks that might be included in (bad) HTML content. This is the only thing that would really break the JSON by accidentally terminating the string early. Any
"
characters should be encoded as"
if it is meant to be included as HTML content.
via
You should escape the forward slash too, here is the correct JSON:
[{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs<\/h2><pclass=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology <\/p>"
}]