I'm using node.js to handle ajax request and return a object back.
我正在使用node.js来处理ajax请求并返回一个对象。
If I use res.json(obj);
, then I get a string
, and I can use JSON.parse(string)
to convert it to object, everything is fine.
如果我使用res.json(obj);,那么我得到一个字符串,我可以使用JSON.parse(string)将其转换为对象,一切都很好。
But if I use res.json(JSON.stringify(obj))
, I can also get a string
, but the JSON.parse(string)
won't convert it to object.
但是,如果我使用res.json(JSON.stringify(obj)),我也可以获得一个字符串,但JSON.parse(字符串)不会将其转换为对象。
What's the difference between the two string
? Their content look the same. I was using the typeof()
to check them.
这两个字符串有什么区别?他们的内容看起来一样。我正在使用typeof()来检查它们。
1 个解决方案
#1
0
So res.json
makes use of JSON.stringify (see line 242) but it does make its own edits by specifying its own json replacer
and json spaces
.
所以res.json使用了JSON.stringify(参见第242行),但它确实通过指定自己的json替换器和json空间来进行自己的编辑。
These are both things JSON.stringify
can take in to alter how it stringifies the JSON. After looking deeper, it seems like json spaces
and json replacer
aren't set by default so Express simply makes it so that if they are set in your apps settings, it will pull them and make sure your JSON responses match up correctly.
这些都是JSON.stringify可以用来改变它对JSON进行字符串化的方式。在深入研究之后,似乎默认情况下没有设置json空间和json替换器,因此Express只是简单地使它如果在应用程序设置中设置它们,它将拉动它们并确保您的JSON响应正确匹配。
It also does some things like setting the Content type, etc.
它还做了一些事情,比如设置内容类型等。
#1
0
So res.json
makes use of JSON.stringify (see line 242) but it does make its own edits by specifying its own json replacer
and json spaces
.
所以res.json使用了JSON.stringify(参见第242行),但它确实通过指定自己的json替换器和json空间来进行自己的编辑。
These are both things JSON.stringify
can take in to alter how it stringifies the JSON. After looking deeper, it seems like json spaces
and json replacer
aren't set by default so Express simply makes it so that if they are set in your apps settings, it will pull them and make sure your JSON responses match up correctly.
这些都是JSON.stringify可以用来改变它对JSON进行字符串化的方式。在深入研究之后,似乎默认情况下没有设置json空间和json替换器,因此Express只是简单地使它如果在应用程序设置中设置它们,它将拉动它们并确保您的JSON响应正确匹配。
It also does some things like setting the Content type, etc.
它还做了一些事情,比如设置内容类型等。