解析带有特殊字符的JSON

解析带有特殊字符的JSON

本文介绍了解析带有特殊字符的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flot进行一些图形绘制,并且在通过我的json传递tickSize时遇到了一些麻烦.我正在使用MVC并在模型中传递json.这是在我的javascript函数中获取json的一些代码:

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:

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

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

Here is how the Json looks leaving the controller:

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

我遇到麻烦的部分是"TickSize".如您所见,"[1,'day']"带有方括号.我认为存在一些解析问题,因为[]通常表示数组. Flot希望此格式的刻度大小.如何构造我的Json,以便可以抓住TickSize?

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?

推荐答案

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

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

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

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

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

但是,您甚至不需要引用和解析JSON,因为它是从JavaScript语法派生的:

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

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

如果需要字符串表示形式,则可以在JavaScript中将其字符串化:

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

var json = JSON.stringify(data):

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

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

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

这篇关于解析带有特殊字符的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:15