简体   繁体   English

如何在JSON字符串化中使用特殊字符?

[英]How to use special characters in JSON stringify?

I am trying to stringify my json code for sending it to MVC controller. 我正在尝试对我的json代码进行字符串化,以将其发送到MVC控制器。 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. 在这种情况下,JSON.stringify返回一个空白数组。 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. 首先,你用array声明的是不正确的,这应该是一个对象,但是无论哪种情况你都需要检查对象和数组之间的区别,但是我假设demo是一个具有两个键/属性的对象,它将被发送到服务器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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