开发者

How can I emulate php's json_encode in javascript / node js using JSON.stringify?

I'm looking for a way to mi开发者_开发技巧mic php's json_encode's behavior from node js. Here's an example showing what php does with a url that is in an object that gets json_encoded:

<?
$foo['url'] = "http://example.com/note/that/the/slashes/get/backslashed";
echo json_encode($foo);
?>

generates the following output:

{"url":"http:\/\/example.com\/note\/that\/the\/slashes\/get\/backslashed"}

Using node.js and the JSON.stringify function here:

var foo = new Object();
foo.url = "http://example.com/note/that/the/slashes/do/not/get/backslashed"
console.log(JSON.stringify(foo));

I observe this output instead:

 {"url":"http://example.com/note/that/the/slashes/do/not/get/backslashed"}

Do you know of a clean way to get JSON.stringify to behave the same way that PHP behaves?

Extra information: I realize that these slashes may not be required for correct json encoding but I am sending json encoded objects to a remote server that I don't have control over and doesn't like them without the backslashes.

More extra information: And I tried putting in my own backslashes and then calling JSON.stringify but JSON.stringify dutifully does properly escape the backslashes so I ended up with \\/ instead of \/ which is what I wanted.


If it's only the slashes you can replace the / with \/ after the conversion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜