简体   繁体   中英

How I format a json of dict

msg = '{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}'
print msg.format(**{'currency': 'usd', 'market': 'btc'})

I want to format this but I get an error.

Traceback (most recent call last):
  File "/Users/wyx/bitcoin_workspace/fibo/tests/t_ws.py", line 21, in <module>
    print msg.format(**{'currency': 'usd', 'market': 'btc'})
KeyError: '"event"'

I even don't know why I get this error.

In a format string { and } are reserved characters indicating a group you wish to replace. If you actually want either of those characters in the string, you need to double them, as {{ and }} , like so:

>>> msg = '{{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}}'
>>> print msg.format(**{'currency': 'usd', 'market': 'btc'})
{"event":"addChannel","channel":"ok_sub_spotusd_btc_trades"}

You may use

msg = "{"+'{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}'+"}"

Otherwise it will be interpreted "event" as a key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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