[英]How to convert nested numpy arrays in a dictionary to JSON?
I'm parsing nested dictionaries, which have different degrees of how nested they are (dictionaries within dictionaries within dictionaries, etc.) I do not know beforehand to what degree the dictionaries are nested.我正在解析嵌套字典,它们具有不同程度的嵌套(字典中的字典等)。我事先不知道字典的嵌套程度。
The problem is, certain dictionary values are numpy.ndarrays
.问题是,某些字典值是numpy.ndarrays
。 When I try to write the dictionary my_dictionary
to JSON with当我尝试将字典my_dictionary
写入 JSON 时
with open(my_dictionary, 'w') as f:
json.dump(my_dictionary, f, indent=4)
I will get the following error:我会收到以下错误:
TypeError: Object of type ndarray is not JSON serializable
Naturally, one way to overcome this would be to simply convert all numpy.ndarray
values into a list with .tolist()
.自然,解决这个问题的一种方法是简单地将所有numpy.ndarray
值转换为带有.tolist()
的列表。
However, given I do not know how nested the dictionaries are, how could I algorithmically check all values of any nested dictionary and convert ndarray
to list?但是,鉴于我不知道字典的嵌套程度,我如何通过算法检查任何嵌套字典的所有值并将ndarray
转换为列表?
Or is there another way to overcome this error?还是有另一种方法来克服这个错误?
You can make custom json.JSONEncoder
.您可以制作自定义json.JSONEncoder
。 For example:例如:
import json
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
data = {"data": [{"obj": np.array([1, 2, 3])}]}
print(json.dumps(data, cls=MyEncoder, indent=4))
Prints:印刷:
{
"data": [
{
"obj": [
1,
2,
3
]
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.