尝试将嵌套dict转换为JSON时出现“TypeError:类型为int64的对象不可JSON序列化”

vyswwuz2  于 2023-02-26  发布在  其他
关注(0)|答案(2)|浏览(217)

我有一个嵌套的字典,我尝试使用json.dumps(unserialized_data), indent=2)将其转换为JSON。

{
  "status": "SUCCESS",
  "data": {
    "cal": [
      {
        "year": 2022,
        "month": 8,
        "a": [
          {
            "a_id": 1,
            "b": [
              {
                "abc_id": 1,
                "val": 2342
              }
            ]
          }
        ]
      },
      {
        "year": 2022,
        "month": 9,
        "a": [
          {
            "a_id": 2,
            "b": [
              {
                "abc_id": 3,
                "val": 2342
              }
            ]
          }
        ]
      }
    ]
  }
}

如何将int64类型的所有整数转换为int,同时不影响dict的结构和任何其他数据类型的值?

b4qexyjb

b4qexyjb1#

如果blhsing的条件不适用,可以递归地深入字典,并将任何np.int64转换为int

def cast_type(container, from_types, to_types):
    if isinstance(container, dict):
        # cast all contents of dictionary 
        return {cast_type(k, from_types, to_types): cast_type(v, from_types, to_types) for k, v in container.items()}
    elif isinstance(container, list):
        # cast all contents of list 
        return [cast_type(item, from_types, to_types) for item in container]
    else:
        for f, t in zip(from_types, to_types):
            # if item is of a type mentioned in from_types,
            # cast it to the corresponding to_types class
            if isinstance(container, f):
                return t(container)
        # None of the above, return without casting 
        return container

from_typesto_types是容器,其中相应的元素给予了要转换的源类型和要转换的目标类型。通过此函数运行字典,然后将其转储到json:

import numpy as np
import json

d = {
  "str_data": "foo bar",
  "lst": [ np.int64(1000), np.float64(1.234) ],
  "dct": {"foo": "bar", "baz": np.float64(6.789), "boo": np.int64(10)}
}

print(json.dumps(d, indent=2)) # throws error

print(json.dumps(
         cast_type(d, 
             [np.int64, np.float64],
             [int,      float]), 
         indent=2))

将字典打印为JSON:

{
  "str_data": "foo bar",
  "lst": [
    1000,
    1.234
  ],
  "dct": {
    "foo": "bar",
    "baz": 6.789,
    "boo": 10
  }
}

在线试用

nbysray5

nbysray52#

如果您的dict中唯一不能进行JSON序列化的对象都是int64类型,那么您可以通过将int设置为默认函数来转换JSON不能序列化的对象,从而轻松地将它们序列化:

json.dumps(unserialized_data, indent=2, default=int)

相关问题