JSON.parse() 返回一个字符串而不是对象

Dor*_*ore 5 javascript json

我不想提出一个新问题,尽管已经就同一主题提出了很多问题,但我确实不知道为什么这不起作用。

我尝试使用以下代码创建 JSON 对象:

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

decodeJSON功能:

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

console.log(post)返回以下 JSON 字符串:

{'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}
Run Code Online (Sandbox Code Playgroud)

扫描完字符串后,我非常确定 JSON 是有效的并且没有语法错误。但是,当运行时JSON.parse(p),我得到的不是一个对象,而是一个字符串。可能是什么原因?

Nit*_*esh 1

您的代码中的问题是您正在JSON.stringify对字符串本身执行操作。因此,解析该字符串的结果将是一个字符串。实际上,您已字符串化两次并解析一次。如果你再次解析它,你将得到一个 JSON。但为了解决方案,请避免两次字符串化。

替换为您的代码。

var p = decodeJSON('{{post.as_json}}');
Run Code Online (Sandbox Code Playgroud)

那可行