luqita
luqita

Reputation: 4077

Making a good json with str.replace

I noticed that if I put double quotes on my input boxes that get passed to php via json, json_decode will return null. Thus, I decided to replace double quotes with \" when making my json.

Thus, I have something like:

var valueToSet = input.replace(/"/gi, '\\"');

The code above replaces "" with \" ... This works, and now I can input stuff like:

Hello hi "" " " " ' ' '' ' ' ' """ 

without breaking anything. However, if I input something like:

Hello hi "" \ "

it gets broken. How can I include to the above replace that slashes get also replaced? And what should I replace slashes with? with \\ ?

Thanks!

Upvotes: 0

Views: 345

Answers (2)

stivlo
stivlo

Reputation: 85476

You should not worry about these issues. I think you're buiding your JSON by hand, while you should use a dedicated function that will take care of those details for you.

  • YUI JavaScript library has a JSON object with a JSON.stringify method that will work in all browsers and will use the native implementation if present.
  • Newer browsers implement JSON.stringify (IE from version 8.0, Firefox from version 3.5, Chrome from version 4.0, Safari from version 4.0, Opera from version 10.5)
  • Douglas Crockford, has written a JSON library
  • On the server side, PHP has json_encode
  • There is support for any other server side language, see json.org for details

To answer your last question, yes, \ should be replaced with \\, but again, it should be done by json_encode.

Upvotes: 2

Spudley
Spudley

Reputation: 168685

Creating a JSON string in Javascript is typically done by creating the array or object you want to turn into JSON, and then running the stringify() method on it.

For example:

var myData = {....some stuff here....};
var myJSON = JSON.stringify(myData);

See this page on json.org for more info: http://www.json.org/js.html

However, note that JSON stringify and parse functionality is not available in all browsers. If you need to support older browsers, you may need to use a library to add this functionality. Libraries such as jQuery include JSON encoding functionality, and there are also stand-alone JSON libraries availble.

Upvotes: 2

Related Questions