Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 211
Ravi Kumar Avatar asked Sep 15 '25 04:09

Ravi Kumar


1 Answers

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));
like image 117
Navoneel Talukdar Avatar answered Sep 16 '25 18:09

Navoneel Talukdar