2017-08-19 53 views
1
msg = '{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}' 
print msg.format(**{'currency': 'usd', 'market': 'btc'}) 

我想格式化,但我得到一个错误。如何格式化字典的JSON

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

我什至不知道为什么我得到这个错误。

+0

一个** **便宜的方法是使用'replace',即'msg.replace('{currency}','usd')。replace('{market}','btc')',它会起作用,但不是正确的做法。 – Bijoy

+0

哪里'msg'来自? –

回答

1

您可以使用

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

否则它将被解释"event"作为重点。

3

格式字符串{}是保留字符,表示您希望替换的组。如果你真的想字符串中这些字符的任意,你需要加倍他们,{{}},像这样:

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