0

As JSON values are generated dynamically and the values in it are based on user inputs, So if user inputs an unacceptable character like " in a string it will make the json invalid.

something like:

{
     "tag" : "demo",
     "value": "user " input" 
}

Is there a way to encode or escape the JSON values?

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • 3
    Um, you use a JSON API. *Don't* try to build up the JSON as a string manually, any more than you would do so for XML. Now, are you actually asking in Javascript or in C#? I can give an example in C#, but I'd find it harder to do in Javascript. – Jon Skeet Jul 17 '16 at 12:32
  • @JonSkeet I'm using it both in C# and javascript. Could you please recommand some APIs? – Ashkan Mobayen Khiabani Jul 17 '16 at 12:34
  • 1
    Well in C# I'd use Json.NET if I were you. I don't know what the appropriate recommendation would be in Javascript, but I'm sure a bit of research will find you lots of options. – Jon Skeet Jul 17 '16 at 12:38
  • 1
    In JavaScript `JSON.parse` and `JSON.stringify`. – gcampbell Jul 17 '16 at 12:39
  • Funny, there was [another question](http://stackoverflow.com/q/38420652/6303733) an hour ago in Java doing the same thing (closed as duplicate of [this question](http://stackoverflow.com/q/19176024/6303733)). – gcampbell Jul 17 '16 at 12:41
  • Thanks a lot Jon Skeet and gcampbell – Ashkan Mobayen Khiabani Jul 17 '16 at 12:41

1 Answers1

1

You should use JSON.stringify for this. It will add escape character \ automatically.

Following is a sample:

function processValues(){
  var v1 = document.getElementById("txt1").value;
  var v2 = document.getElementById("txt2").value;
  var o = {
    value1: v1,
    value2: v2
  };
  var result = JSON.stringify(o);
  console.log(result);
}

function test1(){
  document.getElementById("txt1").value = "Hello";
  document.getElementById("txt2").value = 'World! "test"';
}

test1();
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<button onclick="processValues()">Create JSON string</button>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Rajesh thanks for your answer. What should I do for the json generated on server side via c# – Ashkan Mobayen Khiabani Jul 17 '16 at 12:40
  • If you are sending an object, then no issues. If you are sending string, then you will have to use `JSON.parse`. Note: if you are using MVC 4+, you can look into WebApi, which are data driven controllers. If not, there are many libraries that can help you convert Lists into JSON object – Rajesh Jul 17 '16 at 12:43