为什么typeof JSON.parse返回字符串

问题描述 投票:0回答:1

简要说明

[我将bottle.py用作简单的Web服务器,并呈现了一个javascript,将其传递给python字典,然后在javascript文件中,我想向该对象添加另一个字段,并使用结果进行发布请求。

但是,当我在likePost()中记录typeof数据时,返回的是字符串,因此我无法将新属性添加到该对象。

也尝试了不使用JSON.Stringify()并返回以下错误:Unexpected token ' in JSON at position

代码

    function commentPost(post){
        var comment = prompt("Comment:", "Great post I like it")
        data = JSON.parse(JSON.stringify(post))
        console.log(typeof data)                      // RETURNS STRING
        data.comment = comment                        // THIS DOESN'T WORK
        fetch("/post", {
            method: "POST", 
            body: JSON.stringify(data)
        }).then(res => {
            likePost(data)       
        });

    }
Console.log(发布)
{'hashtag': 'landscapephotography', 'shortcode': 'B_5b0IWqrRU', 'display_url': 'https://scontent-mad1-1.cdninstagram.com/v/t51.2885-15/e35/s1080x1080/95910887_233194497953707_7239044831960646903_n.jpg?_nc_ht=scontent-mad1-1.cdninstagram.com&_nc_cat=107&_nc_ohc=i179pDQmui0AX82O3nB&oh=676ca07cba3af57944abcba4d3a27ad2&oe=5EDE8D74', 'thumbnail_src': 'https://scontent-mad1-1.cdninstagram.com/v/t51.2885-15/sh0.08/e35/s640x640/95910887_233194497953707_7239044831960646903_n.jpg?_nc_ht=scontent-mad1-1.cdninstagram.com&_nc_cat=107&_nc_ohc=i179pDQmui0AX82O3nB&oh=1ff2ac0b031bcc7cbdbb64b2a661ea1b&oe=5EDF0745', 'is_video': False, 'comments_disabled': False, 'caption': 'Photo by Jelen Girona on May 07, 2020.', 'comments_count': 0, 'timestamp': 1588877630, 'owner': '15642627659', 'likes_count': 0}
Console.log(帖子类型)

string

javascript bottle
1个回答
0
投票

如果您的JSON.parse(JSON.stringify(post))结尾为字符串,那么我想您的post也为字符串。

这意味着您只需要使用JSON.parse

之所以失败,是因为有效的JSON只能包含双引号。试试:

JSON.parse(post.replace(/\'/g, '"'))

对于您的情况(我刚刚看到了您更新的问题),虽然您的源代码返回的首字母大写为False,但尝试上述操作后,您会得到一个新的错误。

未捕获的SyntaxError:JSON中位置617处的意外令牌F

如果无法使API正确返回,则也必须.replace

const posts = "{'hashtag': 'landscapephotography', 'shortcode': 'B_5b0IWqrRU', 'display_url': 'https://scontent-mad1-1.cdninstagram.com/v/t51.2885-15/e35/s1080x1080/95910887_233194497953707_7239044831960646903_n.jpg?_nc_ht=scontent-mad1-1.cdninstagram.com&_nc_cat=107&_nc_ohc=i179pDQmui0AX82O3nB&oh=676ca07cba3af57944abcba4d3a27ad2&oe=5EDE8D74', 'thumbnail_src': 'https://scontent-mad1-1.cdninstagram.com/v/t51.2885-15/sh0.08/e35/s640x640/95910887_233194497953707_7239044831960646903_n.jpg?_nc_ht=scontent-mad1-1.cdninstagram.com&_nc_cat=107&_nc_ohc=i179pDQmui0AX82O3nB&oh=1ff2ac0b031bcc7cbdbb64b2a661ea1b&oe=5EDF0745', 'is_video': False, 'comments_disabled': False, 'caption': 'Photo by Jelen Girona on May 07, 2020.', 'comments_count': 0, 'timestamp': 1588877630, 'owner': '15642627659', 'likes_count': 0}"

const postsObject = JSON.parse(posts.replace(/\'/g, '"').replace(/False/g, 'false'));
console.log(postsObject);
© www.soinside.com 2019 - 2024. All rights reserved.