简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM