简体   繁体   English

Javascript:JSON.stringify无法正常工作

[英]Javascript: JSON.stringify not working as expected

I'm pulling JSON data from Wikipedia. 我正在从Wikipedia中提取JSON数据。 However, I can't get it to stringify neatly and I don't understand why. 但是,我无法将其整齐地分类,而且我也不明白为什么。

Here's my code. 这是我的代码。

request({url:formQuery(query), encoding:"utf8"}, (err, res, body) => {
    if (err) handleErr(err)
    console.log(JSON.stringify(body, null, 3))
})

If I just use plain console.log(body), the JSON outputs like this: 如果我仅使用普通的console.log(body),则JSON输出如下所示:

{"continue":{"rvcontinue":"20160314150329|710029514","continue":"||"},"query":{"normalized":[{ ...

But if I use stringify (as above), it looks like this: 但是,如果我使用stringify(如上所述),它看起来像这样:

"{\"continue\":{\"rvcontinue\":\"20160314150329|710029514\",\"continue\":\"||\"},\"query\":{\"normalized\":[{ ...

Stringify is adding a quote to the beginning of the string and escaping subsequent ones. Stringify会在字符串的开头加上引号,并转义后面的引号。

Why is this happening? 为什么会这样呢? Any help would be welcome. 任何帮助都将受到欢迎。

Your JSON data is fine, the function add's slashes to the output because there are quotes in the input. 您的JSON数据很好,该函数在输出中添加斜杠,因为输入中包含引号。 The quotes around property names doesn't have to to be escaped to avoid conflicts when parsing the JSON string/output 解析JSON字符串/输出时,不必转义属性名称周围的引号以避免冲突

I needed to parse the body string into a JSON object first. 我需要首先将主体字符串解析为JSON对象。 If I parse the body string, it works. 如果我解析主体字符串,它就可以工作。

This works fine: 这工作正常:

request({url:formQuery(query), encoding:"utf8"}, (err, res, body) => {
    if (err) handleErr(err)
    let json = JSON.parse(body);
    console.log(JSON.stringify(json, null, 3))

})

Without using stringify , you can use as below. 不使用stringify,可以按以下方式使用。

var oResultData = {"continue":{"rvcontinue":"1111","continue":"1111111"}};
var myRvcontinue = oResultData.continue.rvcontinue;
console.log(myRvcontinue); // 1111

This is because the result of your request is already a string representing your object. 这是因为请求的结果已经是代表对象的字符串。 If you stringify it again (as you do), you obtain a string representing a string representing your object. 如果再次对其进行字符串化(如您所做的那样),则会获得一个字符串,该字符串表示一个表示对象的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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