Javascript 使用特殊字符解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10080208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:44:55  来源:igfitidea点击:

Parsing JSON with special characters

javascriptjsonmodel-view-controllerflot

提问by aelstonjones

I am using flot to do some graphing and I am having some trouble passing the tickSize with my json. I am using MVC and pass the json in a model. Here is some code to grab the json within my javascript function:

我正在使用 flot 来做一些绘图,但我在用我的 json 传递 tickSize 时遇到了一些问题。我正在使用 MVC 并在模型中传递 json。这是在我的 javascript 函数中获取 json 的一些代码:

var json = '<%=Model.Json %>';
var data = jQuery.parseJSON(json);

Here is how the Json looks leaving the controller:

这是 Json 离开控制器的样子:

{\"GraphData\":[{\"X\":1333929600000,\"Y\":0.0},{\"X\":1333670400000,\"Y\":0.46}],\"Max\":1333324800000,\"Min\":1333929600000,\"TickSize\":\"[1, 'day']\"}

The part that I am having trouble with is "TickSize." As you can see, "[1, 'day']" has the square brackets. I think there is some parsing problem because [] usually means an array. Flot wants the tick size in this format. How do I construct my Json so I can grab the TickSize?

我遇到问题的部分是“TickSize”。如您所见,“[1, 'day']” 带有方括号。我认为存在一些解析问题,因为 [] 通常表示一个数组。Flot 需要这种格式的刻度大小。我如何构建我的 Json 以便我可以获取 TickSize?

采纳答案by Jonathan Lonowski

The issue is the single-quotes in the string value, since you're trying to wrap the JSON string in them as well. The resulting JavaScript will be (truncated):

问题在于字符串值中的单引号,因为您还试图将 JSON 字符串包装在其中。生成的 JavaScript 将被(截断):

var json = '...,\"TickSize\":\"[1, 'day']\"}';

Because of the now 4-count of single-quotes, dayisn't actually part of the string and creates a syntax error.

由于现在有 4 个单引号,day它实际上不是字符串的一部分并产生语法错误。

But, you shouldn't even need to quote and parse the JSON since it's derived from JavaScript syntax:

但是,您甚至不需要引用和解析 JSON,因为它源自 JavaScript 语法:

var data = <%= Model.Json %>;

If you need the string representation, you can either stringify it in JavaScript:

如果您需要字符串表示,您可以在 JavaScript 中对其进行字符串化:

var json = JSON.stringify(data):

Or escape single-quotes within the string server-side:

或者在字符串服务器端转义单引号:

var json = '<%= Model.Json.Replace("'", "\'") %>';

回答by Vincent McNabb

It is because you have surrounded the string with 'instead of ". This is causing the string to terminate with your first '.

这是因为您用'而不是将字符串括起来"。这导致字符串以您的第一个'.

Rewrite your first line as

将您的第一行重写为

var json = "<%=Model.Json %>";

回答by Vaibhav.Inspired

Solution :replace single backslash '\' with double '\\' back slash.
For Newline character '\n' to '\\n'
Works with Tooltip messages

解决方案:用双 '\\' 反斜杠替换单反斜杠 '\'。
对于换行符 '\n' 到 '\\n'
与工具提示消息一起使用