简体   繁体   中英

JSON.parse() returns a string instead of object

I'd hate to open a new question even though many questions have been opened on this same topic, but I'm literally at my ends as to why this isn't working.

I am attempting to create a JSON object with the following code:

                var p = JSON.stringify(decodeJSON('{{post.as_json}}'))
                var post = JSON.parse(p);
                console.log(post); // Debug log to test if code is valid

And the decodeJSON function:

    function decodeJSON(json) {
        var txt = document.createElement("textarea");
        txt.innerHTML = json;
        return txt.value.replace(/u'/g, "'");
        }

console.log(post) returns the following JSON string:

{'content': 'kj fasf', 'uid': '4eL1BQ__', 'created': '07/09/2017', 'replies': [], 'tags': ['python'], 'by': {'username': 'Dorian', 'img_url': '/static/imgs/user_Dorian/beaut.jpg'}, 'likes': 0}

After scanning through the string I am pretty sure that the JSON is valid and there are no syntax errors. However, when running JSON.parse(p) Instead of receiving an object, I get a string back. What could be the cause?

That's because decodeJSON returns a string, and JSON.stringify turns that string in another string .

In the other hand, you used JSON.strigify() method on a string. You should stringify an object , not string .

JSON.stringify() turns a javascript object to json text and stores it in a string.

When you use JSON.parse you obtain the string returned by decodedJSON function, not object.

Solution:

var p = JSON.stringify('{{post.as_json}}');
var post = JSON.parse(p);
console.log(post);

It gives me Uncaught SyntaxError: Unexpected token ' in JSON at position 1

The solution is to modify your decodeJSON method.

function decodeJSON(json) {
    var txt = document.createElement("textarea");
    txt.innerHTML = json;
    return txt.value.replace(/u'/g, '\"');
}

var p = decodeJSON('{{post.as_json}}');
var post = JSON.parse(p);
console.log(post); 

The issue in your code is that you are performing JSON.stringify on a string itself. So on parsing the result of this string will be a string. In effect, you have stringified twice and parsed once. If you parse it once more you will get a JSON. But for solution avoid the stringification twice.

Replace in your code.

var p = decodeJSON('{{post.as_json}}');

That will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM