2011-09-01 131 views
0

我正在尋找一種方法來模仿php的json_encode從節點js的行爲。這裏是展示一個URL,它是在一個對象被json_encoded做什麼PHP的一個例子:如何使用JSON.stringify在javascript/node js中模擬php的json_encode?

<? 
$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盡職盡責地避免了反斜槓,所以我最終用\\ /而不是\ /這正是我想要的。

回答

5

如果只是斜槓,則可以用\/替換/的轉換。

+0

哈!我怎麼看不到?謝謝! – Hugh