gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:50 24 4
gpt4 key购买 nike

我正在寻找一种从 Node 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 尽职尽责地正确转义了反斜杠,所以我最终得到了\\/而不是\/这就是我想要的。

最佳答案

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

关于php - 如何使用 JSON.stringify 在 javascript/node js 中模拟 php 的 json_encode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7275984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com