How to use special characters in JSON stringify?

10,188

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));
Share:
10,188
Ravi Kumar
Author by

Ravi Kumar

Updated on June 14, 2022

Comments

  • Ravi Kumar
    Ravi Kumar almost 2 years

    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?