如何将嵌套dict中的所有int转换为strjson.dumps文件()?

2024-10-17 00:31:15 发布

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

我有,一个输入,整数。我用它们(作为价值观)构建了一个dict。然后我将其转储到JSON,以便在其他地方重用。在

我最终(在“别处”)需要使用这些整数作为字符串。因此我可以进行转换

  • 上游(构建dict时)
  • 或在接收端(“别处”)。在

无论解决方案是什么,代码中都会有大量的str()。 把所有的清洁剂都转换成特定的。在

一个想法是在recursively parse the dict构建完成后,在{}之前,进行转换。 不过,我想知道,在转储JSON的同时,是否没有一种方法来处理这个问题?可能是用json.JSONEncoder?(坦率地说,我不太明白)


Tags: the方法字符串代码jsonparse地方整数
1条回答
网友
1楼 · 发布于 2024-10-17 00:31:15

假设在接收端运行Python,可以在加载JSON时使用parse_int参数将int转换为字符串:

import json

test = {'foo':1, 'bar':[2,3]}
json_str = json.dumps(test)
print(json.loads(json_str, parse_int=str))

收益率

^{pr2}$

Per the docs

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

相关问题 更多 >