[javascript] Write HTML string in JSON

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

This question is related to javascript jquery html json

The answer is


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


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

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.


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

_x000D_
_x000D_
{_x000D_
  [_x000D_
    {_x000D_
      "id": "services.html",_x000D_
      "img": "img/SolutionInnerbananer.jpg",_x000D_
      "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>"_x000D_
    }_x000D_
  ]_x000D_
}
_x000D_
_x000D_
_x000D_


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.


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?


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

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");

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

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 :)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?