首页 > 解决方案 > TypeError:NAType 类型的对象不是 JSON 可序列化的

问题描述

预先感谢您的帮助。

我的 python 代码读取 json 输入文件并将数据加载到数据框中,对配置指定的数据框列进行掩码或更改,并在最后阶段创建 json 输出文件。

read json into data frame --> mask/change the df column ---> generate json

输入json:

[
    {
        "BinLogFilename": "mysql.log",
        "Type": "UPDATE",
        "Table": "users",
        "ServerId": 1,
        "BinLogPosition": 2111
    },        {
    {   "BinLogFilename": "mysql.log",
        "Type": "UPDATE",
        "Table": "users",
        "ServerId": null,
        "BinLogPosition": 2111
    },
  ...
]

当我将上述 json 加载到数据框中时,数据框列“ServerId”具有浮点值,因为它在几个 json 输入块中为 null。

主要的中央逻辑将“ServerId”转换/伪造为另一个数字,但输出包含浮点数。

输出json:

[
      {
            "BinLogFilename": "mysql.log",
            "Type": "UPDATE",
            "Table": "users",
            "ServerId": 5627.0,
            "BinLogPosition": 2111
        }, 
        {
            "BinLogFilename": "mysql.log",
            "Type": "UPDATE",
            "Table": "users",
            "ServerId": null,
            "BinLogPosition": 2111
        },
     ....
]

屏蔽逻辑

df['ServerId'] = [fake.pyint() if not(pd.isna(df['ServerId'][index])) else np.nan for index in range(len(df['ServerId']))]

挑战在于,输出“ServerId”应该只包含整数,但不幸的是它包含浮点数。

df['ServerId']
0     9590.0
1        NaN
2     1779.0
3     1303.0
4        NaN

我找到了这个问题的答案,使用“Int64”

df['ServerId'] = df['ServerId'].astype('Int64')
0     8920
1     <NA>
2     9148
3     2434
4     <NA>

然而,使用'Int64',它将 NaN 转换为 NA 并且在写回 json 时,我得到一个错误,

TypeError:NAType 类型的对象不是 JSON 可序列化的

with gzip.open(outputFile, 'w') as outfile:
    outfile.write(json.dumps(json_objects_list).encode('utf-8'))

转换为“Int64”数据类型后是否可以保留 NaN?如果这是不可能的,我该如何解决这个错误?

标签: pythonpandasdataframenumpypython-3.8

解决方案


推荐阅读