我怎么能迭代地创建一堆JSON类型的字符串文字?

时间:2018-01-01 16:28:10

标签: python json

所以,我有以下内容:

values = """ { "exchange_code": "GDAX", "exchange_market": "BTC/USD", "type": "asks" } """

正如您所知,""",值必须是字符串文字。但是,我想生成几个值,这些值只有第一个键" exchange_code"的值已更改。我如何能够使用for循环进行迭代,并创建几个相同类型的字符串文字,只更换第一个值?到目前为止,我发现没有任何东西逃脱它,对str的类型转换在生成正确的输出方面不起作用。

1 个答案:

答案 0 :(得分:3)

使用json模块解析字符串,更改您喜欢的结果字典的任何部分,然后再将它们转储为json-strings。

>>> import json
>>> values = """ { "exchange_code": "GDAX", "exchange_market": "BTC/USD", "type": "asks" } """
>>> 
>>> d = json.loads(values)
>>> alternatives = ['XADG', 'ABCD']
>>> 
>>> result = []
>>> for alt in alternatives:
...     d['exchange_code'] = alt
...     result.append(json.dumps(d))
... 
>>> result
['{"type": "asks", "exchange_code": "XADG", "exchange_market": "BTC/USD"}', '{"type": "asks", "exchange_code": "ABCD", "exchange_market": "BTC/USD"}']

或者作为Python 3中更简洁的理解:

>>> [json.dumps({**d, 'exchange_code': alt}) for alt in alternatives]
['{"type": "asks", "exchange_market": "BTC/USD", "exchange_code": "XADG"}', '{"type": "asks", "exchange_market": "BTC/USD", "exchange_code": "ABCD"}']