Python 如何格式化dict的json
我想格式化这个,但我得到一个错误Python 如何格式化dict的json,python,json,Python,Json,我想格式化这个,但我得到一个错误 msg = '{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}' print msg.format(**{'currency': 'usd', 'market': 'btc'}) 回溯(最近一次呼叫最后一次): 文件“/Users/wyx/bitcoin_workspace/fibo/tests/t_ws.py”,第21行,在 打印消息格式(**{‘货币’:‘美元’
msg = '{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}'
print msg.format(**{'currency': 'usd', 'market': 'btc'})
回溯(最近一次呼叫最后一次):
文件“/Users/wyx/bitcoin_workspace/fibo/tests/t_ws.py”,第21行,在
打印消息格式(**{‘货币’:‘美元’,‘市场’:‘btc’})
KeyError:““事件””
我甚至不知道为什么会出现这个错误。您可以使用
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"'
否则它将被解释为一个键。您可以使用
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"'
否则,它将被解释为一个键。格式字符串中的
{
和}
是表示要替换的组的保留字符。如果您确实想要字符串中的任何一个字符,则需要将它们加倍,如{{
和}
,如下所示:
msg = "{"+'{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}'+"}"
在格式字符串
{
和}
中,是表示要替换的组的保留字符。如果您确实想要字符串中的任何一个字符,则需要将它们加倍,如{{
和}
,如下所示:
msg = "{"+'{"event":"addChannel","channel":"ok_sub_spot{currency}_{market}_trades"}'+"}"
一个便宜的方法是使用
replace
,即msg.replace({currency}',usd')。replace({market}',btc')
,它可以工作,但不是正确的方法。msg
来自哪里?一个便宜的方法是使用replace
,即msg.replace({currency}',usd')。replace({currency}',美元')。replace({market}',btc')
,它会起作用,但不是正确的方法。msgmsg
来自哪里?