Michael W
Michael W

Reputation: 343

How could I iteratively create a bunch of JSON-type string literals?

So, I have the following:

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

As you can tell by the """, the values needs to be a string literal. However, I want to generate several values that just have an altered value for the first key "exchange_code". How would I be able to iterate with a for loop, and create several string literals of the same sort with just the first value replaced? So far nothing I found escapes it, typecasting to str does not work in terms of generating correct output.

Upvotes: 1

Views: 41

Answers (1)

timgeb
timgeb

Reputation: 78650

Parse the string with the json module, change whatever parts of the resulting dictionary you like and dump them as json-strings again.

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

Or as a little more concise comprehension in 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"}']

Upvotes: 3

Related Questions