I'm looking for a way to mimic 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.

share|improve this question

feedback

1 Answer

up vote 4 down vote accepted

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

share|improve this answer
Ha! How did I not see that? Thanks! – Hugh Sep 1 '11 at 20:22
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.