0

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.

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ha! How did I not see that? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.