"TypeError: Object of type int64 is not JSON serializable" while trying to convert a nested dict to JSON

huangapple go评论59阅读模式
英文:

"TypeError: Object of type int64 is not JSON serializable" while trying to convert a nested dict to JSON

问题

这是您要翻译的内容的翻译部分:

我有一个嵌套字典我试图使用`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,同时保持字典的结构和其他数据类型的值不受影响?

英文:

I have a nested dictionary that I am trying to convert to JSON using json.dumps(unserialized_data), indent=2). The dictionary currently looks like this:

{
  "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
              }
            ]
          }
        ]
      }
    ]
  }
}

How can I convert all integers of type int64 to int while leaving the structure of the dict and values of any other data type unaffected?

答案1

得分: 3

如果您的字典中唯一无法进行JSON序列化的对象都是类型为int64,您可以通过将int作为默认函数来将它们轻松序列化,以便JSON无法序列化的对象:

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

If the only objects in your dict that aren't JSON-serializable are all of type int64, you can easily serialize them by making int the default function for converting objects that JSON can't serialize:

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

答案2

得分: 1

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

def cast_type(container, from_types, to_types):
    if isinstance(container, dict):
        # 转换字典中的所有内容
        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):
        # 转换列表中的所有内容
        return [cast_type(item, from_types, to_types) for item in container]
    else:
        for f, t in zip(from_types, to_types):
            # 如果项目属于from_types中提到的类型之一,
            # 则将其转换为相应的to_types类
            if isinstance(container, f):
                return t(container)
        # 除此以外,不进行转换返回
        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)) # 报错

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
  }
}

在线尝试

英文:

If blhsing's condition doesn't apply, you can drill down recursively into the dictionary and cast any np.int64 to 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_types and to_types are containers where corresponding elements give the type to convert from, and the type to convert to.
Run your dictionary through this function, then dump it to 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))

Prints the dictionary as JSON:

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

Try online

huangapple
  • 本文由 发表于 2023年2月24日 12:09:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定