Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 1 year ago 43
JSON Question

Encoding JSON data to preserve the json format

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?

Answer Source

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);

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

<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<button onclick="processValues()">Create JSON string</button>