如何使用JSON.stringify在javascript / node js中模拟php的json_encode?

时间:2011-09-01 20:15:25

标签: php json node.js stringify

我正在寻找一种模仿来自节点js的php的json_encode行为的方法。这是一个示例,显示了php对一个获取json_encoded的对象中的url所做的事情:

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

生成以下输出:

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

在这里使用node.js和JSON.stringify函数:

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

我观察此输出:

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

你知道一种简洁的方法让JSON.stringify的行为方式与PHP的行为相同吗?

额外信息:我意识到正确的json编码可能不需要这些斜杠但是我将json编码的对象发送到我无法控制的远程服务器,并且在没有反斜杠的情况下不喜欢它们。

更多额外信息:我尝试放入自己的反斜杠然后调用JSON.stringify,但JSON.stringify尽职尽责地正确转义反斜杠,所以我最终得到了\\ /而不是\ /这就是我想要的。< / p>

1 个答案:

答案 0 :(得分:5)

如果只是斜杠,您可以在转换后用/ 替换\/