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?

6
  • 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. Commented Jul 17, 2016 at 12:32
  • @JonSkeet I'm using it both in C# and javascript. Could you please recommand some APIs? Commented Jul 17, 2016 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. Commented Jul 17, 2016 at 12:38
  • 1
    In JavaScript JSON.parse and JSON.stringify. Commented Jul 17, 2016 at 12:39
  • Funny, there was another question an hour ago in Java doing the same thing (closed as duplicate of this question). Commented Jul 17, 2016 at 12:41

1 Answer 1

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>

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

2 Comments

Rajesh thanks for your answer. What should I do for the json generated on server side via c#
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

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.