我用的是numpy.float32个数字,而不是JSON.克服这个问题的正确方法是什么?

import numpy as np
import json

a = np.float32(1)
json.dumps(a)

TypeError: Object of type 'float32' is not JSON serializable

推荐答案

It has to be a string, so you can have:

json.dumps(str(a))

EDIT:

JSON is a format for serialising object data. It doesn't really care or know about Python types, the json package tries to translate whatever object you pass json.dumps() into a string form via a conversion table that only supports some types (see doc below).

这就是为什么我认为传递一个字符串来避免这个问题是个好主意:numpy.float32不在表中.

因为有些人 comments 说,显式地将字符串传递给dumps"听起来是错误的",所以我将在这里添加文档

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().

Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.

taken from the official docs here: https://docs.python.org/3/library/json.html

Json相关问答推荐

JOLT拉平数组

时间序列的Vega Lite分组条形图

NIFI-我需要数组的信息,但只需要第一个信息

使用自定义类型在Golang中解析JSON数组

将 REST API - json 输出转换为表 Power BI

使用 JOLT 将日期格式转换为 JSON

jq如何合并两个json对象

ETCD 导出为 json 并从 base64 解码所有键/值到人类可读

嵌套 JSON 到 CSV(多级)

TSQL FOR JSON 嵌套值

解析 JSON API 响应

如何在golang中获取 struct 的json字段名称?

python,将Json写入文件

在 C# 中解析 Json rest api 响应

Java的JSON字符串整洁/格式化程序

jQuery循环.each()JSON键/值不起作用

在 React 中访问子级的父级状态

设置对象不是 JSON 可序列化的

如何从 BindingResult 获取控制器中的错误文本

Volley JsonObjectRequest Post 参数不再起作用