从Python通过Request传递NaN到javascript



我有一个包含np的pandas数组。NaN转换成JSON的字典

json_data = {"freq" : list(df["Data"])}

我准备通过flask jsonify加载到一个网页

@dashboard.route('/command', methods = ['GET', 'POST'])
def command():
[...]
return jsonify(json_data)

在javascript端,我准备好读取它

$.ajax({
url: '/dashboard/command',
type: 'POST', 
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json', 
success: function(msg) {
if (!msg.error) {
updatePlot(msg);
}
else {
alert(msg.error);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There has been an error retrieving your data: nn" + errorThrown);
},
complete: function() {
$("#update-plot").prop('disabled', false);  // Re-enable button
$("#update-plot-loading").addClass('invisible');  // Hide loading animation
}

如果我加载那个网页,它就会在这里结束。它说它有一个坏的标记"N"在json。如果我在尝试发送之前替换NaN,例如

df["Data"].replace(np.NaN, -999.999)

,一切正常,javascript可以继续。我知道NaN应该是"null"。在javascript方面,所以我现在做的是将-999.999转换为"null"…但是,天哪,难道不应该有一种直接发送丢失数据的方法吗?

有什么建议吗?我尝试了NaN, "NaN", None等许多组合。但也许我错过了一个。我检查了python上jsonify的输出,它似乎是一个有效的响应。

谢谢,t .

啊哈。算是进步吧。至少在Flask端是这样,也许Ajax不是。考虑一只熊猫里面有一些np.Nan…转换成字典或者其他什么然后调用render_template

s = render_template('dashboard/dashboard_horizontal.html', 
average_data = average_data)

这就是造成损害的地方....但它是可以用

修复的
s = s.replace("nan", "NaN")      #this is dumb but works!!

json中的false出现了一个相关的问题。当您将其读入Python时,解析器方便地将其转换为False。除了现在你在Javascript端产生了问题,但它也可以用同样的方式修复。

s = s.replace("False", "false")      #this is dumb too

我不知道是否有一些关键字可以传递给render_template自动做到这一点?

好的,我也有一个关于NaN的Ajax解决方案,这就是这里解释的JSON5思想:如何解析包含"NaN"的JSON字符串;在Node.js中。具体来说,不要使用dataType json,使用'text'并手动进行解析。

$.ajax({
url: '/dashboard/command',
type: 'POST',   
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'text',            // it was 'json'
//async: false,
success: function(msg) {
if (!msg.error) {
var data = json5.parse(msg);  // json5 so much more friendly
updatePlot(data);
}
else {
alert(msg.error);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error:nn" + errorThrown);
},
complete: function() {
$("#update-plot").prop('disabled', false);  // Re-enable button
$("#update-plot-loading").addClass('invisible');   
}
});
}

最新更新