1

I'm pulling JSON data from Wikipedia. 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:

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

But if I use stringify (as above), it looks like this:

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

Stringify is adding a quote to the beginning of the string and escaping subsequent ones.

Why is this happening? Any help would be welcome.

4
  • Maybe you want an object? Try with JSON.parse(...); Commented Apr 18, 2016 at 9:25
  • body it's already a string, thats why you stringify and get that output Commented Apr 18, 2016 at 9:25
  • JSON.stringify converts json to string...that's correct output Commented Apr 18, 2016 at 9:27
  • 1
    Yes. I needed to convert the body into a JSON object using parse. Commented Apr 18, 2016 at 9:32

4 Answers 4

1

Your JSON data is fine, the function add's slashes to the output because there are quotes in the input. The quotes around property names doesn't have to to be escaped to avoid conflicts when parsing the JSON string/output

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

Comments

1

I needed to parse the body string into a JSON object first. 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))

})

3 Comments

The only "JSON object" is the one that is built–in. There are strings formatted as JSON that can be parsed to create objects.
So you get a string encoded JSON, you decode it, then you string encode it again. Isn't it a bit counterproductive? The only reason for this is if you need a human readable encoding.
@QuentinRoy That's what it looks like OP intends because of the additional parameters being passed in.
0

Without using stringify , you can use as below.

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

Comments

0

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.

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.