10

I have a textbox that posts info to the server and it's in JSON format. Lets say I want to enter two quotes for the value, and the JSON struct would look like:

{
    "test": """"
}

I need it to look like:

{
    "test": "\"\""
}

so it will follow JSON standards and can be parsable/stringifyable.

I tried using

 var val = myVal.replace('"', "\\\"");

but this didn't work. val ends up with only one escaped quote like so \""Any help is much appreciated!

5
  • 4
    What does "this didn't work" mean? What didn't work? What happened? Show us a testcase to work with. Aug 12, 2011 at 18:03
  • should't you do the conversion before you put data in JSON? Aug 12, 2011 at 18:05
  • what do you want to do with the escaped string?
    – Baz1nga
    Aug 12, 2011 at 18:05
  • Textboxes don't "post" anything on their own. And you haven't been clear about how your interface is used. Does your script build a JSON string? Does the user enter all of it? Show us your code. Aug 12, 2011 at 18:07
  • 1
    Cut me some slack, I had to rush to get to a meeting on time.
    – Darcy
    Aug 12, 2011 at 19:01

4 Answers 4

14

My answer makes some assumptions, as I've had to fill in the rather sizeable gaps in your question:

  • The user will enter a text string into a textbox;
  • Your script will read the textbox contents, and use those contents as the value of one of the items in a JSON string that it's building;
  • The script sends this resulting JSON string to the server somehow.

If I've got that right, let's proceed...


Baseline code

So, with some placeholders, you're doing:

function get_contents_of_textbox() {
   // Dummy data for example
   return 'My mum pushed and I said "Hello World"!';
}

function send_to_server(json_str) {
   // Dummy action: display JSON string
   console.log(json_str);
}

var myVal = get_contents_of_textbox();
var JSON  = '{ "test": "' + myVal + '" }';
send_to_server(JSON);

Live demo, showing the malformed JSON.


Initial attempt

To ensure that JSON is valid, escape any quotes and backslashes that it may contain. You already gave it a go:

myVal = myVal.replace('"', "\\\"");

and the result of your attempt is:

{ "test": "My mum pushed and I said \"Hello World"!" }

Only the first quote has been escaped. This is because only one instance of the search string is replaced by default.

The Mozilla documentation says:

To perform a global search and replace, either include the g flag in the regular expression or if the first parameter is a string, include g in the flags parameter.


Working attempt

Unfortunately, the flags parameter is non-standard, so let's switch to the regex version of replace, and use the /g switch in it:

myVal = myVal.replace(/"/g, '\\"');

(You'll notice that I also condensed the replacement string, for brevity.)

Result:

{ "test": "My mum pushed and I said \"Hello World\"!" }

Live demo. Hurrah!


Complete solution

Let's also add logic to escape backslashes, and we end up with this:

function get_contents_of_textbox() {
   // Dummy data for example
   return 'My mum pushed [a back\\slash] and I said "Hello World"!';
}

function send_to_server(json_str) {
   // Dummy action: display JSON string
   console.log(json_str);
}

var myVal = get_contents_of_textbox();
myVal = myVal.replace(/\\/g, '\\\\'); // escape backslashes
myVal = myVal.replace(/"/g, '\\"');   // escape quotes

var JSON  = '{ "test": "' + myVal + '" }';
send_to_server(JSON);

Result:

{ "test": "My mum pushed [a back\\slash] and I said \"Hello World\"!" }

Live demo.

6

Use this

var val = myVal.replace(/"/g, '\\"');
2
  • One replace and three backslashes in second argument. :)
    – user882255
    Aug 12, 2011 at 18:12
  • @Darcy: My answer points out some other considerations that you need to make. It also explains the problem. Be sure to read it. Aug 12, 2011 at 19:19
0

Just create a JS array

var arr = {
   test: '""'
}

and let the JSON interface handle the escaping for you. You shouldn't ever have to deal with the details yourself.

7
  • I think there's more going on here, but can't be sure until the OP expands on what he's doing. Aug 12, 2011 at 18:06
  • 2
    (Also, this is not an array. Please stop propagating that rubbish.) Aug 12, 2011 at 18:06
  • 1
    @Tomalak took my a long time to realise JSON and javascript objects were actually different things...
    – Endophage
    Aug 12, 2011 at 18:09
  • Also, agreed, that's not an array! It's an object. @Marc B arrays use [] not {} and are only numerically indexed in JS. Objects just have the nice functionality of allowing array style access.
    – Endophage
    Aug 12, 2011 at 18:10
  • 1
    I've decided to downvote. There's no indication that there's any "JSON interface" here. I'm sure now that the OP is just building a JSON string.. and this is not the same thing as a Javascript object. Aug 12, 2011 at 18:23
0

As you said you're getting the string from a textbox you don't need to do anything to it to get it back to the server. If you get the value of the textbox via jQuery's $() notation or pure document.getElementById it will already be properly escaped. JavaScript doesn't take the value of your textbox and try to put it in quotes.

If you text box has "" entered into it, document.getElementById('mytextbox').value is not equal to "\"\"". The backslashes are only necessary when you are defining a string literal.

Try removing all your escaping and regex replacing and just send back the data from the text box without doing anything to it. Your json should look something like:

{
    "test" : document.getElementById('myTextBox')
}

Your Answer

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

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