I'm beginner with JSON and I'm very confused with this.
I have to convert any valid JSON string into valid HTML string to be able to visualize JSON on the web.
jsonToHtml(“[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]") => “x:1x:100"
Thank you guys.
I'm beginner with JSON and I'm very confused with this.
I have to convert any valid JSON string into valid HTML string to be able to visualize JSON on the web.
jsonToHtml(“[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]") => “x:1x:100"
Thank you guys.
First, you've got some issues with your single and double quote characters. It looks like maybe a copy and paste issue. The JSON you're showing is an acceptable syntax to create an array of objects, just remove the wrapping double quotes.
Use chrome's JavaScript console to paste in the following:
var myVar = [{'x': 1, 'b': 2}, {'x': 100, 'b': 200}]
// myVar now contains an array of the two objects.
// Test it out by attempting to access one of the objects properties.
myVar[0].b
If the target browser supports ECMAScript 5, you can use the native JSON.parse function.
// Your JSON
var myJson = '[{"x": 1, "b": 2}, {"x": 100, "b": 200}]';
// Call our handy function that parses the JSON and set our variable with the parsed results.
var parsedObject = parseJson(myJson);
function parseJson(json) {
return JSON.parse(json);
}
What about this one :
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
var jsonString = "[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]";
var htmlString = htmlEscape(jsonString);
Based on this post.