Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>"     } ] 
like image 208
Rasmikant Avatar asked Mar 21 '14 06:03

Rasmikant


People also ask

Can HTML be stored in JSON?

The problem with HTML inside JSON is that HTML elements have properties that must use double quotes. But as soon as you insert double quotes it's going to cause syntax error because JSON can only do double quotes.

How escape HTML tag JSON?

You're HTML values are OK, but the keys of the JSON object must be enclosed in quotes. string. quotation marks. Also, if you output this JSON object inside the script tags of an HTML page, you must escape the "</" sequence of HTML closing tags, as per this appendix in the HTML 4 specification.

Can we convert HTML to JSON in JavaScript?

What you want to do is called serializing. var json = JSON. stringify({html:html}) , that is JSON. What you have is simply a javascript object, no such thing as a "JSON object".


2 Answers

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

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

like image 190
Sahil Mittal Avatar answered Oct 03 '22 23:10

Sahil Mittal


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"); 
like image 31
Mahesh Avatar answered Oct 03 '22 22:10

Mahesh