46

Is it possible to write an HTML string inside JSON?

Which I want to write like below in my JSON file:

[
    {
        "id": "services.html",
        "img": "img/SolutionInnerbananer.jpg",
        "html": "<h2 class="fg-white">AboutUs</h2><p class="fg-white">developing and supporting complex IT solutions. Touching millions of lives world wide by bringing in innovative technology.</p>"
    }
]
1
  • 2
    I don't know much about JSON, but i think you should use escape sequences for quotes after class, " like \".
    – skrtbhtngr
    Mar 21, 2014 at 6:20

15 Answers 15

40

You should escape the characters like double quotes in the html string by adding "\"

eg: <h2 class=\"fg-white\">

3
  • I have changed my code as below but still it is showing validation error in JSONLint validator [ { "id": "services.html", "img": "img/SolutionInnerbananer.jpg", "html": "<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">we are pioneer in providing consulting, developing and supporting complex IT solution<\/p>" } ]
    – Rasmikant
    Mar 21, 2014 at 8:54
  • 1
    You sure? I just checked here: jsonlint.com and its saying that its a "valid JSON" Mar 21, 2014 at 8:57
  • Ya. It is a valid JOSN. Thank You very much
    – Rasmikant
    Mar 21, 2014 at 10:15
26

Just encode html using Base64 algorithm before adding html to the JSON and decode html using Base64 when you read.

byte[] utf8 = htmlMessage.getBytes("UTF8");
htmlMessage= new String(new Base64().encode(utf8));


byte[] dec = new Base64().decode(htmlMessage.getBytes());
htmlMessage = new String(dec , "UTF8");
9

You can, once you escape the HTML correctly. This page shows what needs to be done.

If using PHP, you could use json_encode()

Hope this helps :)

2
  • If you echo ' " ' the content will be escaped automatically by PHP.
    – B.F.
    Sep 26, 2014 at 8:38
  • json_encode works:- $design=file_get_contents('test.html'); $design=json_encode($design); $json = '{"message":{"html": '.$design.'}}'; Nov 8, 2021 at 8:42
8

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 &quot; if it is meant to be included as HTML content.

via

0
7

Lets say I'm trying to render the below HTML.

let myHTML = "<p>Go to this <a href='https://google.com'>website </b></p>";
JSON.parse(JSON.stringify(myHTML))

This would give you a HTML element which you can set using innerHTML.

Like this

document.getElementById("demo").innerHTML = JSON.parse(JSON.stringify(myHTML));

People are storing their HTML as an object here. However the method I suggested does the same without having to use an Object.

1
4

It is possible to write an HTML string in JSON. You just need to escape your double-quotes.

[
    {
        "id": "services.html",
        "img": "img/SolutionInnerbananer.jpg",
        "html": "<h2class=\"fg-white\">AboutUs</h2><pclass=\"fg-white\">CSMTechnologiesisapioneerinprovidingconsulting,
        developingandsupportingcomplexITsolutions.Touchingmillionsoflivesworldwidebybringingininnovativetechnology,
        CSMforayedintotheuntappedmarketslikee-GovernanceinIndiaandAfricancontinent.</p>"
    }
]
2
  • I have changed my code as below but still it is showing validation error in JSONLint validator [ { "id": "services.html", "img": "img/SolutionInnerbananer.jpg", "html": "<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">we are pioneer in providing consulting, developing and supporting complex IT solution<\/p>" } ]
    – Rasmikant
    Mar 21, 2014 at 8:53
  • 1
    What about single quotes? Oct 28, 2020 at 23:13
2

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>"
}]
1

If you are using Vue, you can use the v-html directive.

<div class="columns>
    <p v-html="resource.body"></p>
</div>
0

The easiest way is to put the HTML inside of single quotes. And the modified json object is as follows:

[
    {
        "id": "services.html",
        "img": "img/SolutionInnerbananer.jpg",
        "html": '<h2 class="fg-white">AboutUs</h2><p class="fg-white">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology </p>'
    }
];

Fiddle.

And the best way is to esacape the double quotes and other characters that need to be escaped. The modified json object is as follows:

[
    {
        "id": "services.html",
        "img": "img/SolutionInnerbananer.jpg",
        "html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology </p>"
    }
];

Fiddle.

1
  • 3
    wrapping around single quotes doesn't work if you want valid json object.
    – Marcio
    Jun 4, 2015 at 10:05
0

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>"}
0
0

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?

3
  • 2
    There is not "standard HTML format" that gets "violated" by using single quotes. Single quotes in HTML is perfectly valid HTML! Nov 2, 2016 at 23:13
  • You're right, I was looking at it from a conventions perspective. The vast majority prefer to use double quotes for HTML attribute values. I've updated my answer to reflect this. Nov 5, 2016 at 17:17
  • I've used single quotes in the html successfully when returned as a json string. It will validate as valid json as well.
    – Rickchip
    May 1, 2019 at 20:39
0

in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \

and everything in json file wrapped in {} change your json to

{
  [
    {
      "id": "services.html",
      "img": "img/SolutionInnerbananer.jpg",
      "html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"
    }
  ]
}

0

You can use html online editor, i.e, Every html tag and brackets have some html entity value ,convert those tags specially brackets into corresponding entity value examples

<h1>Hello<h1>

can also be wriiten as:

&lt;h1&gt;Hello &lt;/h1&gt;

Html entites

Html editor

Open html write html code and click on source code button For php use this fucntions

0

When I want to add html to json or even whole blocks of html I will do it like this

$html = <<<HTML
    Put here all your html code, you can easy use $variables as well
HTML;
$jsonOBJ['html'] = $html;
echo json_encode($jsonOBJ);
0

This example could help.

let express = require('express')
let app = express()

//HTML in JSON
let jh = [
    {"tag":"h1","text":"hello","style":"background-color: black;color:white","options":""}
]

//Convert JSON into HTML
let tag = (tag,text,style,options)=>{return `<${tag} style="${style}" ${options}>${text}</${tag}>`}

let header = tag(jh[0]["tag"],jh[0]["text"],jh[0]["style"],jh[0]["options"])

//Show on page
app.get('/',(req,res)=>{
    res.send(header)
})

app.listen('5000')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.