未定义类型的对象不可JSON序列化

2024-05-23 22:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在将JSON从flask传递到JavaScript时,我面临一个问题:(

错误显示为TypeError: Object of type Undefined is not JSON serializable。我想这是因为数据类型,但我在flask_app.py文件中使用了data_1 = data_1.to_dict('records'),这使得数据类型看起来像:

[{'Station': 'Taipei', 'Code': 900, 'GateIn': 8442}, 
{'Station': 'Tainan', 'Code': 910, 'GateIn': 1394}, 
{'Station': 'Taichung', 'Code': 920, 'GateIn': 2770}........
]

如果我想将它传递给Javascript,我认为这是一种正确的JSON类型。这是我的python、html和JS文件,有人能给我一些指导吗

flask_app.py

@app.route("/")
def home(): 
   engine = create_engine('postgresql://postgres@localhost:5394/station_detail')

   df = pd.read_sql(
       sql = "select * from station;",
       con = engine)

   data_1 = df[['name_c','stationcode','gatein']]
   data_1.columns = ['Station','Code','GateIn']
   data_1 = data_1.to_dict('records') 


   return render_template('/html_template/hello.html', geodata = data_1)

app.run()

在html文件中,我调用自己的javascript文件(barchart.js):

HTML:

<script src = "{{url_for('static',filename='javascript/barchart.js')}}"></script> <html> <div class=”canvas”> </div> <canvas id="myChart" width="400" height="200" role="img"> </canvas> </html> <script> var data_1 = JSON.parse('{{ geodata | tojson | safe}}'); var ctx = document.getElementById('myChart').getContext('2d'); var chart = barchart(data_1,ctx); console.log(data_1) </script>

barchart.js

function barchart(data, ctx) { var GateInData = data.map(function (d) { return +d.GateIn; }); var stationLabels = data.map(function (d) { return d.Station; }); var chart = new Chart(ctx, { type: bar, data: { labels: stationLabels, datasets: [{ data: GateInData,}]}, options: { scales: { yAxes: [{ ticks: { beginAtZero: true}}]}}}); return chart }

Tags: 文件jsonappflaskdatareturnvarhtml
1条回答
网友
1楼 · 发布于 2024-05-23 22:32:21

错误消息基本上表示您有

[{'Station': 'Taipei', 'Code': 900, 'GateIn': 8442}, 
{'Station': 'Tainan', 'Code': 910, 'GateIn': nothing}, ...

nothing是一个变量,但它没有定义。您需要跟踪此错误的来源并以某种方式处理它,以防在第一时间发生这种情况,或者定义您认为已经定义的变量,或者删除无法序列化的值

(错误消息看起来像是来自Python,但最终数据来自Postgres。可能您的数据库中有一些东西被SQL驱动程序作为Undefined导入。可能还可以参见How do I identify rows with empty / undefined enum values in postgres?

相关问题 更多 >