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

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

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

问题

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

  1. 我有一个嵌套字典我试图使用`json.dumps(unserialized_data), indent=2)`将其转换为JSON该字典当前如下所示
  2. {
  3. "status": "SUCCESS",
  4. "data": {
  5. "cal": [
  6. {
  7. "year": 2022,
  8. "month": 8,
  9. "a": [
  10. {
  11. "a_id": 1,
  12. "b": [
  13. {
  14. "abc_id": 1,
  15. "val": 2342
  16. }
  17. ]
  18. }
  19. ]
  20. },
  21. {
  22. "year": 2022,
  23. "month": 9,
  24. "a": [
  25. {
  26. "a_id": 2,
  27. "b": [
  28. {
  29. "abc_id": 3,
  30. "val": 2342
  31. }
  32. ]
  33. }
  34. ]
  35. }
  36. ]
  37. }
  38. }

如何将所有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:

  1. {
  2. "status": "SUCCESS",
  3. "data": {
  4. "cal": [
  5. {
  6. "year": 2022,
  7. "month": 8,
  8. "a": [
  9. {
  10. "a_id": 1,
  11. "b": [
  12. {
  13. "abc_id": 1,
  14. "val": 2342
  15. }
  16. ]
  17. }
  18. ]
  19. },
  20. {
  21. "year": 2022,
  22. "month": 9,
  23. "a": [
  24. {
  25. "a_id": 2,
  26. "b": [
  27. {
  28. "abc_id": 3,
  29. "val": 2342
  30. }
  31. ]
  32. }
  33. ]
  34. }
  35. ]
  36. }
  37. }

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无法序列化的对象:

  1. 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:

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

答案2

得分: 1

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

  1. def cast_type(container, from_types, to_types):
  2. if isinstance(container, dict):
  3. # 转换字典中的所有内容
  4. return {cast_type(k, from_types, to_types): cast_type(v, from_types, to_types) for k, v in container.items()}
  5. elif isinstance(container, list):
  6. # 转换列表中的所有内容
  7. return [cast_type(item, from_types, to_types) for item in container]
  8. else:
  9. for f, t in zip(from_types, to_types):
  10. # 如果项目属于from_types中提到的类型之一,
  11. # 则将其转换为相应的to_types类
  12. if isinstance(container, f):
  13. return t(container)
  14. # 除此以外,不进行转换返回
  15. return container

from_typesto_types是容器,其中相应的元素提供要从哪种类型转换以及要转换为哪种类型。将您的字典通过此函数运行,然后将其转储为JSON:

  1. import numpy as np
  2. import json
  3. d = {
  4. "str_data": "foo bar",
  5. "lst": [ np.int64(1000), np.float64(1.234) ],
  6. "dct": {"foo": "bar", "baz": np.float64(6.789), "boo": np.int64(10)}
  7. }
  8. print(json.dumps(d, indent=2)) # 报错
  9. print(json.dumps(
  10. cast_type(d,
  11. [np.int64, np.float64],
  12. [int, float]),
  13. indent=2))

以JSON格式打印字典:

  1. {
  2. "str_data": "foo bar",
  3. "lst": [
  4. 1000,
  5. 1.234
  6. ],
  7. "dct": {
  8. "foo": "bar",
  9. "baz": 6.789,
  10. "boo": 10
  11. }
  12. }

在线尝试

英文:

If blhsing's condition doesn't apply, you can drill down recursively into the dictionary and cast any np.int64 to int:

  1. def cast_type(container, from_types, to_types):
  2. if isinstance(container, dict):
  3. # cast all contents of dictionary
  4. return {cast_type(k, from_types, to_types): cast_type(v, from_types, to_types) for k, v in container.items()}
  5. elif isinstance(container, list):
  6. # cast all contents of list
  7. return [cast_type(item, from_types, to_types) for item in container]
  8. else:
  9. for f, t in zip(from_types, to_types):
  10. # if item is of a type mentioned in from_types,
  11. # cast it to the corresponding to_types class
  12. if isinstance(container, f):
  13. return t(container)
  14. # None of the above, return without casting
  15. 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:

  1. import numpy as np
  2. import json
  3. d = {
  4. "str_data": "foo bar",
  5. "lst": [ np.int64(1000), np.float64(1.234) ],
  6. "dct": {"foo": "bar", "baz": np.float64(6.789), "boo": np.int64(10)}
  7. }
  8. print(json.dumps(d, indent=2)) # throws error
  9. print(json.dumps(
  10. cast_type(d,
  11. [np.int64, np.float64],
  12. [int, float]),
  13. indent=2))

Prints the dictionary as JSON:

  1. {
  2. "str_data": "foo bar",
  3. "lst": [
  4. 1000,
  5. 1.234
  6. ],
  7. "dct": {
  8. "foo": "bar",
  9. "baz": 6.789,
  10. "boo": 10
  11. }
  12. }

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:

确定