Pandas将dict存储到json中

2024-03-28 09:58:37 发布

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

有这样一本字典:

    thisdict = {'12': [[1, 970000009], [3, 990000547], [9, 900000007]],
          '3': [[2, 970022209], [3, 990000547]],
          '32': [[4, 94042209], [5, 40547]],
          '6575': [[3, 94334009], [2, 923200547], [6, 7807], [7, 98807], [8, 8887]],
...
     }

如何将此词典保存到json文件中

我尝试了以下代码,但不起作用:

import json
with open('results.json', 'w') as fp:
    json.dump(thisdict, fp)

这是输出中的错误:

Object of type int64 is not JSON serializable

修复此错误的解决方案是什么


Tags: 文件代码importjson字典objectas错误
2条回答

您发布的代码运行良好,并且在您提供的dict部分中没有明显的int64

从字里行间看,这看起来像是numpy数据,因此您的问题可能不是dict值,而是JSON序列化程序无法处理numpy数据类型。对于这个问题,您已经有了可以使用的解决方案,如下所述:Python - TypeError: Object of type 'int64' is not JSON serializable

我重写了你们的代码,改变了字典的数据类型,看到了同样的错误

import json
import numpy as np

thisdict = {'12': [[1, 970000009], [3, 990000547], [9, 900000007]],
            '3': [[2, 970022209], [3, 990000547]],
            '32': [[4, 94042209], [5, 40547]],
            '6575': [[3, 94334009], [2, 923200547], [6, 7807], [7, 98807], [8, 8887]]}
data = list(thisdict.items())
arr = np.array(data)

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

TypeError:类型为ndarray的对象不可JSON序列化

我知道你的字典可能有一个Int64数据类型。请检查此目录的类型

解决方案:

import json
import pandas as pd
import numpy as np

thisdict = {'12': [[1, 970000009], [3, 990000547], [9, 900000007]],
            '3': [[2, 970022209], [3, 990000547]],
            '32': [[4, 94042209], [5, 40547]],
            '6575': [[3, 94334009], [2, 923200547], [6, 7807], [7, 98807], [8, 8887]],
            }

data = list(thisdict.items())
arr = np.array(data)
df = pd.DataFrame(arr)
df.to_json('result.json')

相关问题 更多 >