【问题标题】:saving dictionary into json python将字典保存到 json python
【发布时间】:2017-09-16 10:49:14
【问题描述】:

我对 python 很陌生,我试图创建两个数组或矩阵,将它们注册到字典中,保存到 json 文件中。这是我的代码

import numpy as np
import json
array_1 = np.array([[1,2,3],[4,6,7]])
array_2 = np.array([[4,0],[9,8]])
json_data = {
    'array_1': array_1,
    'array_2': array_2,
 }

import json

with open('json_data.json', 'wb') as fp:
    json.dumps(json_data, fp)

但我收到以下错误:

“ndarray”类型的对象不是 JSON 可序列化的

【问题讨论】:

  • json 模块只知道如何序列化原生 Python 类型,如 listdict 等。您需要将数组作为 Python lists 存储在 @987654327 中@dictionary,或者编写一个由json.dumps调用的函数来自动进行转换。阅读default参数到json.dumps

标签: python json dictionary


【解决方案1】:

首先将其转换为 python 列表,如下所示:

json_data = {
    'array_1': array_1.tolist(),
    'array_2': array_2.tolist()
 }

然后尝试将其转储为 json:

import json

with open('json_data.json', 'w') as fp:
    json.dump(json_data, fp)

【讨论】:

  • 它给了我以下错误:dumps() 接受 1 个位置参数,但给出了 2 个
  • 我只能使用with open('json_data.json', 'w') as fp: json.dump(json_data, fp)
  • @smvpfm: json.dumps() 转储到一个字符串。请改用json.dump()
【解决方案2】:

最好和最简单的方法是:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

【讨论】:

  • 不,它不起作用:TypeError: Object of type 'ndarray' is not JSON serializable
  • 你需要先处理ndarray。这是一种独特的数据类型
【解决方案3】:

首先更正您的数据。 正确数据: json_data = { 'array_1':array_1, 'array_2':array_2 }

在行尾 (array_2) 有一个额外的 ','。这就是您遇到 JSON 序列化问题的原因。

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多