PURE Unobtrusive Rendering Engine

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:

I don’t know much about JSON, but i think you should use escape sequences for quotes after class, » like \» .

15 Answers 15

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

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

» > ]

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 can, once you escape the HTML correctly. This page shows what needs to be done.

If using PHP, you could use json_encode()

json_encode works:- $design=file_get_contents(‘test.html’); $design=json_encode($design); $json = ‘<"message":<"html": '.$design.'>>’;

4 Things You Must Do When Putting HTML in JSON:

1) Escape quotation marks used around HTML attributes like so

2) Escape the forward slash in HTML end tags. Hello World!. This is an ancient artifact of an old HTML spec that didn’t want HTML parsers to get confused when putting strings in a 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
tag as a child of an unordered list that is formatted like so: , it won’t work. It gets added to the DOM after the ul tag. But, if the code looks like this: (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.

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

let myHTML = "

Go to this website

"; JSON.parse(JSON.stringify(myHTML))

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

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.

Источник

Display JSON Data in HTML Page

JSON format is highly used to store data in a structured way. Even data received from a server is in JSON format. Here we will see how to display JSON data in HTML page using JavaScript in form of tables and lists.

JSON data has a structure like a javascript object. Data is stored in key-value pairs, where the key is a string and value can be any type of data.

First, you may think to display these data directly as text on the webpage but this doesn’t look appealing also is not readable.

SSo in this article, we will fetch JSON data from a local or remote server and display it in a better way.

display JSON data in HTML page

Display JSON data in HTML page using JavaScript

To start working with let our JSON data be following. Source link.

Now we will fetch this JSON data from the remote server and display it on the webpage.

To read JSON data from the local or remote servers we will use the fetch() method.

The fetch() method takes the URL of the JSON file as an argument and returns a Promise object.

After resolving the Promise object we will get the JSON data in the Response object.

fetch(URL) // get the JSON data .then(response => response.json()) // use (display) the JSON data .then(data => console.log(data))

We have the JSON data in data stored in a variable. Now we can use it to display the data in the webpage.

1. Display JSON Data As List

To display the JSON data in a list we will create HTML elements dynamically and insert data in them.

Elements we need to create here are ul and li .

Before we start keep the data structure of JSON data in mind. The image below shows to get the first student name we have to use data.result[0].name and to get first student marks we have to use data.result[0].marks , where to access marks of math subject we have to use data.result[0].marks.math .

structure of JSON data

Keeping the above structure in mind we first create a ul element and assign it to a variable.

const mainUL = document.createElement('ul')

This ul element will be the main element any list element ( li ) will represent a student and their marks and will be created dynamically.

Now we can create a for loop that will iterate over the data.result array and create a li element for each student and set innerHTML of the li element to the student name.

Now create another list that will contain all the marks of the student and append it to the li element (studentLI) created just before.

for(let i = 0; i < data.result.length; i++) < const studentLI = document.createElement('li'); studentLI.innerHTML = data.result[i].name; // create list for marks const marksUL = document.createElement('ul'); for(var key in data.result[i].marks) < const marksLI = document.createElement('li'); marksLI.innerHTML = key + ': ' + data.result[i].marksJavascript json html code; marksUL.appendChild(marksLI); >// append marks list to studentLI studentLI.appendChild(marksUL); >

Now we have created a list of students and their marks. Now we can append the ul element to the mainUL element.

// append studentLI to mainUL mainUL.appendChild(studentLI);

Finally, append it to the body. Here is the complete code to display the list of students and their marks.

  

display JSON data as list

2. Display JSON Data As Table

To display the JSON data in a table we will create a function that takes JSON data as an argument and creates a table and append it to the body.

In the function createtable() create the basic structure of the table so that we have the heading of the table as ‘name’ and ‘marks’. Below these marks create another list to show the subject as shown in the code below.

var table = ""; // add a row for name and marks table += ` Name Marks `; // now add another row to show subject table += ` Math English Chemistry Physics `;

Now we can create a for loop that will iterate over the data.result array and create a tr element for each student and set innerHTML of the tr element to the student name.

// now loop through students // show their name and marks var tr = ""; for(let i = 0; i < data.result.length; i++) < tr += ""; tr += `$ `; for (var key in data.result[i].marks) < tr += `$ `; > tr += "" >

Finally, append the table to the body. Here is the complete Javascript code for fetching JSON data and displaying it as a table.

function showTable() < fetch("./lib/examples/students.json") .then(response =>response.json()) .then(data => createTable(data)); > function createTable(data) < var table = ""; // add a row for name and marks table += ` `; // now add another row to show subject table += ` `; // now loop through students // show their name and marks var tr = ""; for(let i = 0; i < data.result.length; i++) < tr += ""; tr += `$ `; for (var key in data.result[i].marks) < tr += `$ `; > tr += "" > table += tr + "
Name Marks
Math English Chemistry Physics
"; // append table to body document.body.innerHTML += table; >

display JSON data as a table

Conclusion

In this short tutorial, we saw how to fetch and display JSON data in HTML pages using javascript. We displayed data as a list and table with a complete explanation of the code.

Источник

Generate HTML page with JS from JSON

I’m looking for a very basic example of using Javascript to parse a JSON file and output an html file or populate an html file. All the examples I’ve located so far have code snippets and I don’t have the background to fill in the blanks between. Thank you for any fiddles (which would be awesome), links, and smart a*s comments.

You mean like var data = JSON.parse(‘<"foo": "42">‘); document.body.appendChild(document.createTextNode(data.foo)); ? Parsing JSON is easy. You can add DOM elements using the appropriate methods ( createElement , appendChild ). Which elements have to be created and which data should be shown depends on what you want, there is no canonical answer for this. It might be even better for you to use templates.

Yes, except the JSON would be on the same server in its’ own file. I just found a fiddle for it I think. jsfiddle.net/qmacro/NJMyD

5 Answers 5

Templating example

I would suggest on of templating tools for example PURE.

The purpose of such a tool is separation of logic and representation.

For example, generating a list from JSON data using mentioned tool would look like this:

JSON data file

       Hello    

This is most basic approach appropriate if you have simple JSON data (see working JSFiddle example there).. Get Started guide will walk you trough another example if basic approach isn’t suitable. For more advanced features take look at the documentation.

Alternatives

There was no particular reason that PURE has been used in above example. There are many other alternatives out there:

. or you can do it manually as explained there.

You can use a microtemplating library, like Mustache, to parse incoming JSON objects into HTML snippets using > template syntax. If your object looks like:

Using Mustache, you can render it into HTML easily using > and > to traverse nested objects:

Mustache.render('Hello, my name is > and I am > years old. > I have > hair and > eyes.>', myObj); 

Hello, my name is Joe Smith and I am 25 years old. I have red hair and blue eyes.

EDIT: more germane application — dynamically generate a control panel using a template with nested lists of objects. Here’s my template and object (HTML broken into a list and joined for clarity):

var panel = [ '
', '>', '
', '

>

', '

', '>', '', '>', '

', '
', '>', '
', ].join('\n'); var panelObj = < cpanel: [ < name: 'playback', content: [ , , ] >, < name: 'zoom', content: [ , ] >] >;

Then you render with Mustache:

Mustache.render(panel, panelObj); 
 

playback

zoom

You might want to look at jQuery.dForm. It helps creating HTML and forms dynamically using JSON.

So i am assuming you mean your JSON contains the HTML string inside it.

you can render this in your HTML by writing your HTML as follows:

   var myjson = now thats smart!
"> function loadHTML()

Note that you can also use AJAX to fetch your JSON and render it however, note that embedding HTML inside JSON when transporting from server is considered a security vulnerability. Instead, you can fetch a partial HTML from the server directly by using AJAX and then replace portions of that HTML (template) with dynamic values by using javascrip and REST/SOA

Источник

Читайте также:  Html запрет контекстного меню
Оцените статью