1

So I am trying to create a JSON explorer / editor. I am able to parse the initial JSON into the div and format it how I like.

this is the function i use 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>`)
}

in order to save the JSON I was going to retrieve the JSON from the text of the div using

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

right now this is able to be parse by JSON.parse(); but when i want to console.log(getJSON()[0]) this returns {

am i not formating the JSON correctly. a live example of this can be found here

1
  • Maybe first do a console.log("${json_text}") and run that through a JSON linter online...? Commented Jun 10, 2021 at 18:52

2 Answers 2

2

First, your console.log result doesn't make sense. A parsed JSON object is now usable in JavaScript and, if has (only) properties x and y, would result in undefined when requesting property 0 as you have. It looks like your call to console.log was to a different (earlier?) version of the getJSON() function, where it returned the raw string, and in that case it makes sense that you're just retrieving the first character of the JSON text: "{".

But then, assuming the version of getJSON() as written, it would actually throw a parse exception:

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

Looking at your site, I was able to do, in the console:

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

That is illegal JSON. JSON specifies (only) the quotation mark " for strings (Unicode/ASCII 0x22) on page 7 of its specification.

The fact that 'partName' is legal as a JavaScript string literal is irrelevant but perhaps confusing.

As a minor style point, simplify JSON.parse(`"${json_text}"`) to JSON.parse(json_text).

Sign up to request clarification or add additional context in comments.

2 Comments

I have made some updates to my site much more of it parses now except for a } I guess at the last position. what can I do to solve this. thanks for your quick response
The format of SO means encapsulated single questions. So you'd have to isolate, describe the issue in detail and post a separate question. Keep the example input as minimal as possible but that still fails.
0

@BaseZen's answer was very helpful for me to understand what was going wrong with my code. My JSON was incorrectly formatted even though online linters say its correct. Along with what BaseZen pointed out, JSON.parse() will not work with trailing commas. To fix this:

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

I found this information at SO post JSON Remove trailiing comma from last object

SO user Dima Parzhitsky's answer was what helped me also figure out this question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.