Creating JSON data that is completely valid using client-side JavaScript

I've been working on creating a JSON explorer/editor. Successfully managed to parse the initial JSON into the div and customize the formatting.

Here's the function I utilize to loop through the initial JSON:

_iterate(_tab, raw_json){
    var tab = _tab;
    tab++;

    for(var key1 in raw_json){
        var data_type = typeof raw_json[key1];
        var d = String(raw_json[key1])
        if(d == String){
           d = "String";
        }
        if(d == Number){
            d= "Number"
        }
        if(data_type == "object" || data_type == "array"){
            this.input.append(`<json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2 -je-${data_type}">'<span class="-je-key">${key1}</span>' :{</div></br>`)
            this._iterate(tab, raw_json[key1])
        }else{
            this.input.append(`<div class="json-editor-row"><json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2">'<span class="-je-key">${key1}<span>:' : '<div class="json-editor-input -je-${data_type}" contenteditable="true" for="{key: '${key1}', data: '${d}'}"></div>', </div></br></div>`)
        }
    }
    
    this.input.append(`<json-tab tab-width="${tab -1}"></json-tab>},</br>`)
}

To save the JSON, my plan was to retrieve the JSON from the text of the div using this function:

getJSON(){
    var json_text = this.input.text().slice(0, -1)
    return JSON.parse(`"${json_text}"`)
}

Currently, this can be parsed by JSON.parse();, however, when attempting console.log(getJSON()[0]), it returns {.

Could it be that I'm not formatting the JSON correctly? You can check out a live demo of this here

Answer №1

Initially, the outcome of your console.log statement appears nonsensical. A JSON object that has been parsed is now functional in JavaScript and, if it contains only properties x and y, attempting to access property 0 would result in undefined, just like you have experienced. It seems like your usage of console.log may have been referring to a different (earlier?) iteration of the getJSON() function, where it returned the raw string. In such a scenario, retrieving the initial character of the JSON text: "{" would make sense.

However, considering the version of getJSON() as presented, it would actually trigger a parsing error:

VM1511:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1

Upon inspecting your website, I managed to execute the following command in the console:

jsonString = $('json-editor').text()
// value: "{'partName' : '', 'partRevision' : '', ..."

This violates JSON syntax rules. JSON strictly requires the use of double quotation marks " for strings (specified on page 7 of its specification).

The validity of 'partName' as a JavaScript string literal is immaterial but could be potentially misleading.

From a minor stylistic perspective, consider simplifying

JSON.parse(`"${json_text}"`)
to JSON.parse(json_text).

Answer №2

After struggling with my code, I came across a helpful solution provided by @BaseZen. It turns out that my JSON formatting was incorrect, despite validation from online tools. In addition to pointing out the issue with my JSON, BaseZen also mentioned that JSON.parse() does not work with trailing commas. To resolve this problem:

_remove_trailing_commas(json_string){
    var regex = /\,(?!\s*?[\{\[\"\'\w])/g;
    return json_string.replace(regex, '');
}

I uncovered this valuable information in an SO post titled JSON Remove trailiing comma from last object

Credit is also due to SO user Dima Parzhitsky for their useful answer that aided me in resolving this issue.

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

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

Function invoking React Hook

I'm a beginner to React JS and I've been learning by working on a project. I was creating a basic e-commerce UI with items and attempting to add items to a cart, but encountered an issue. The React Hook "useStateValue" is being called in the fun ...

You cannot define headers once they have been sent to the client. If you encounter a NextJS redirect issue, consider using res

I encountered an error when redirecting to a link from NextJS -> _app.js -> getInitialProps. I am trying to cache the last user language in cookies and redirect to it when the page is reloaded. It's working and the user is redirected, but I&apos ...

Sketch on canvas using vue framework

I am trying to modify a selection tool using rectangles that was created with JS and HTML in Vue.js. Here is the original version: https://codepen.io/sebastiancz/pen/mdJVJRw initDraw(document.getElementById('canvas')); function initDraw(canvas) ...

When waiting for proxy leads to access the 'then' property, what should be my next move?

In my code, I am using a special Proxy to imitate a virtual object. The getter of this proxy returns values that are already prepared. After some exploration, I found out that when the proxy is awaited, it triggers the 'then' property of the pro ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

PHP API Integration for XBox

Check out this demo link: http://davidwalsh.name/xbox-api I decided to create a php file with the following content.. <?php // Customizations $gamertag = 'RyanFabbro'; $profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamert ...

Using the className prop in a React Component

Struggling to assign a classname to the material-ui Button component. Here are my failed attempts: Attempt 1: attributes.map((attribute, index) => { const classString = 'classes.button' + index; console.log(classString) return ( &l ...

What is the best way to showcase information from multiple JSON files simultaneously?

Creating dynamic JSON URLs based on browser cookie data. var cookie = $.cookie('faved_posts'); The cookie contains IDs like 123456, 111111, 000001, etc. Now we need to request the JSON file for each ID in the cookie. We have: $.each(cookie, ...

Unexpected behavior from Bootstrap within React

I recently started working on a React project that I initiated with the create-react-app command. To incorporate Bootstrap into my project, I added the necessary CDNs to the public/index.html file after generating the project. <link rel="stylesheet" hr ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

ReactJS does not recognize the library mentioned

click here to access the pondjs folder inside node-modulesAfter installing pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application and confirming its presence in package.json, I encountered an issue in App.js. W ...

Execute an ajax function when a form is submitted on Marketo

My Request I am seeking assistance with integrating a Marketo script in a WordPress plugin. Upon submission of the Marketo form, I need to perform calculations using the form elements and display the results on the page. Please provide suggestions on ho ...

What is the best way to organize a table with multiple state variables using nested loops?

What is the best way to display multiple variables in a table using a loop, such as i,j,k? this.state = { materials: ['m1', 'm2'], quantity: ['2', '4'], unitPrice : ['12&apo ...

Take the attention away from the canvas

Is there a way to shift focus away from the canvas and onto input fields in my HTML code? Right now, the canvas is holding onto focus even when I'm clicking on text inputs. This prevents me from typing anything into them. Ideally, I'd like for t ...

Combining column values with AngularJS

What is the best way to merge column values in AngularJS? ...

Tips for resizing mesh along the global axis

Have you ever used an online 3D editor that allows you to manipulate individual meshes by moving, scaling, and rotating them? This editor utilizes custom transform controls inspired by the TransformControls code from three.js. Here is a snippet of code fro ...

How can you ensure that links on Ajax-loaded pages direct users to their intended destinations?

The issue at hand: When clicking on links within dynamically loaded pages, the desired dynamic loading of other pages does not occur. Within my index page, I have links structured like this: <li><a class="page_one" title="page_one" href="page_on ...

When running the command "NPM start" in Gulp, you may encounter a situation where a blank page appears with the error message: "Cannot GET /"

I've been following a comprehensive tutorial on setting up a new desktop app using Angular2, Bootstrap, Yeoman, and Gulp. However, I encounter an issue when trying to test the code locally after reaching the frontend task section. Every time I run np ...

Is there a way to fetch and display property changes in Vue Material's md-dialog?

In the component hierarchy, there is a parent component containing a child, which further contains an md-dialog component. The dialog is opened from the parent component using the following code: ParentComponent.vue <template> <div> < ...