Converting JSON to HTML without the use of external libraries

As a newcomer to JSON, I'm feeling quite puzzled by it.

I need to transform a legitimate JSON string into a valid HTML string in order to display JSON on the web.

jsonToHtml(“[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]") => “x:1x:100"

Your help is greatly appreciated.

Answer №1

What's your opinion on this particular code snippet :

function escapeHTML(str) {
    return String(str)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

var jsonData = "[{‘x’: 1, ‘b’: 2}, {‘x’: 100, ‘b’: 200}]";
var escapedString = escapeHTML(jsonData);

Referencing this insightful discussion.

Answer №2

It seems like there are some issues with the single and double quote characters in your code, possibly due to a copy and paste error. The JSON format you've provided is correct for creating an array of objects, just make sure to remove the unnecessary double quotes.

To test this out, you can use Chrome's JavaScript console and paste the following code:

var myVar = [{'x': 1, 'b': 2}, {'x': 100, 'b': 200}]
// Now myVar will contain an array of two objects.
// Try accessing one of the object properties to verify it works.
myVar[0].b

UPDATE

If the browser supports ECMAScript 5, you can utilize the built-in JSON.parse function.

// Your JSON data
var myJson = '[{"x": 1, "b": 2}, {"x": 100, "b": 200}]';
// Call a custom function parseJson to parse the JSON data and store the results in parsedObject variable.
var parsedObject = parseJson(myJson);
function parseJson(json) {
  return JSON.parse(json);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

Is there a Node.js method that is similar to jQuery AJAX's .complete() function

In the process of creating a Node.js API to enroll a user in a different web application, I encountered an issue. As part of the registration flow, the API called by the Node app using request is being redirected with a status code of 301 to another API to ...

Parsing JSON into Java objects with custom parsers

Is there a custom JSON to Java object parser available that can map JSON properties to Java object attributes through a configuration? Let's say I have a class: class Person { String id; String name; String loc;} The JSON string I have is: {name:" ...

Neglecting single quotes in Jquery functions

i am struggling with this particular function function getTextfieldonly(fieldName, id) { var option = jQuery('#'+fieldName+'_textfield').val(); if (option != "") { $('.'+fieldName+'_ul'). ...

Encountered a TypeError in Angular printjs: Object(...) function not recognized

I'm currently working on integrating the printJS library into an Angular project to print an image in PNG format. To begin, I added the following import statement: import { printJS } from "print-js/dist/print.min.js"; Next, I implemented the pri ...

Comparing npm start and running the app with node app.js

I'm brand new to exploring the world of Node and understanding the basics of app development. I find it interesting how these two commands seem to have a similar output: node app.js --compared to-- npm start Both commands appear to continue "l ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Is there a way to identify the duplicated input element values using jquery?

Just starting out in the world of web development and jQuery. I have an input element that has been bound with a blur event. Here's the code snippet: // Here are my input elements: <input class="input_name" value="bert" /> <input class="inp ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

Creating Vue components based on a deeply nested data structure

Is there a way to efficiently utilize a nested object for generating Vue components? My nested object structure is as follows: "api": { "v1": { "groups": { "create": true, "get": true, ...

Developing custom functions in ejs for individual posts

In my blog, I have a feed where all users' posts are displayed dynamically using ejs. There is a comment section that remains hidden until the user clicks the comments button. Below is a snippet of my ejs file: <% posts.forEach(post => { %> ...

Encode image into base64 format without the need for file uploads

Is there a way to save an image in localStorage in base64 format without uploading it? I want to convert an existing image into base64. Can someone provide guidance on how to achieve this? function loadImageFileAsURL() { var filesSelected = document ...

What steps should I follow to develop a REST API that can retrieve a JSON or XML file from a client?

In need to create a PHP RESTful service that can exchange JSON data with the user - sending JSON and receiving either JSON or XML. While I have experience in sending JSON or XML data, I'm unsure about how to properly retrieve data from the user. ...

Utilizing JSON for live population of search filter results

I'm currently developing a search function for my website that will sift through a JSON Object using regular expressions. My goal is to have the results displayed in real time as the user types, similar to how Google shows search suggestions. However ...

Encountered an issue with importing a TypeScript module

One issue I encountered is that when importing a module in an app.ts script, the '.js' extension is not included in the import line of the compiled js file. In my app.ts file, I have import {ModuleA} from './ModuleA' After compilation ...

Having trouble with prettyphoto functionality

Seeking assistance as I am struggling to get this working Here is how I have set it up: <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen"/ ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Struggling to integrate the c3 chart library with Angular, encountering loading issues

I've been attempting to utilize the c3 angular charts, but unfortunately nothing is displaying on my page. Despite checking for console errors and following a tutorial, I still can't seem to get anything to show up. I have cloned the git repo an ...

Unable to modify information retrieved from API. Error: Unable to assign to property that is set to read-only

Using an API call, I retrieve some data. getPosts(postRequest: PostRequest): void { this._postService.getPosts(postRequest).subscribe(result => { const postList = result as PostList this.posts = postList.posts }); ...

Navigate to a specific element using Selenium WebDriver in Java

Currently, I am utilizing Selenium along with Java and ChromeDriver to execute a few scripts on a website. My goal is to scroll the driver or the page to a specific element positioned on the webpage. It is important that this element is visible. I am awa ...