简体   繁体   English

如何使用json.dumps()将所有int转换为嵌套dict中的str?

[英]how to convert all int to str in a nested dict with json.dumps()?

I have, an an input, integers. 我有一个输入整数。 I build a dict out of them (as values). 我用它们构建了一个字典(作为值)。 I then dump it to JSON, to be reused elsewhere. 然后我将其转储到JSON,以便在其他地方重用。

I ultimately (at the "elsewhere") need to use these integers as strings. 我最终(在“其他地方”)需要将这些整数用作字符串。 I can therefore do the conversion 因此,我可以进行转换

  • upstream (when building the dict) 上游(建立字典时)
  • or on the receiving side (the "elsewhere"). 或在接收方(“其他地方”)。

There will be, no matter the solution, plenty of str() all over the code. 无论解决方案如何,代码中都会有大量的str() I am looking for a cleaner way to convert all the int into str in that specific case. 我正在寻找一种更简洁的方法,在特定情况下将所有int转换为str

One idea is to recursively parse the dict once it is built, just before the json.dumps() , and make the conversion there. 一个想法是在构建之后递归解析dict ,就在json.dumps()之前,并在那里进行转换。 I am wondering, though, if there is not a way to handle this while dumping the JSON? 我想知道,如果在转储JSON时没有办法处理这个问题? Possibly with json.JSONEncoder ? 可能与json.JSONEncoder (which to be frank I do not understand much) (坦白说我不太了解)

Assuming that on the receiving end you are running Python, you could convert the ints to strings upon loading the JSON by using the parse_int parameter: 假设在接收端运行Python,您可以在使用parse_int参数加载JSON时将整数转换为字符串:

import json

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

yields 产量

{u'foo': '1', u'bar': ['2', '3']}

Per the docs : 根据文档

parse_int , if specified, will be called with the string of every JSON int to be decoded. 如果指定了parse_int ,将使用要解码的每个JSON int的字符串调用。 By default this is equivalent to int(num_str). 默认情况下,这相当于int(num_str)。 This can be used to use another datatype or parser for JSON integers (eg float). 这可以用于为JSON整数使用另一种数据类型或解析器(例如float)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM