Ravi Kumar
Ravi Kumar

Reputation: 43

How to use special characters in JSON stringify?

I am trying to stringify my json code for sending it to MVC controller. But it does not work when data contains some special characters like greater than > or less than sign <.

Here is Sample code

 function demo()
 {
     debugger
     var demo = [];
     demo.one = 'one';
     demo.two = '<just>'
     var treeBinding = JSON.stringify(demo);
     $.ajax({
         url: '/flow/demo',
         type: "GET",
         data: { dd: treeBinding },
         success: function (res) {

         },
         error: function (error) {
             alert(error)
         }
     });
 }

JSON.stringify returns a blank array in this case. Can anyone help me to get it worked?

Upvotes: 4

Views: 15501

Answers (2)

Rajesh
Rajesh

Reputation: 24915

You can try something like this:

function arrayToObjectString(arr) {
  var returnSrt = "{";
  for (var key in arr) {
    returnSrt += "\"" + key + "\" : \"" + arr[key] + "\"";
    returnSrt += ","
  }
  returnSrt = returnSrt.substring(0, returnSrt.length - 1) + "}";

  return returnSrt;
}

function main() {
  var demo = [];
  demo.one = 'one';
  demo.two = '<just>'

  console.log(JSON.stringify(demo))

  var resultStr = arrayToObjectString(demo);
  
  console.log(resultStr)
  console.log(JSON.parse(resultStr));
}

main();

Upvotes: 0

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4588

First of all your declaration with array is incorrect.That is supposed to be an object but whatever case you need to check difference between object and array.However I assume that demo is an object with two key/properties which will be sent to server.

So declaration should look like this-

     var demo = {};
     demo.one = 'one';
     demo.two = '<just>';

Then you should use to escape -

var treeBinding = encodeURIComponent(JSON.stringify(demo));

Upvotes: 9

Related Questions