[英]Python - dump dict as a json string
我錯過了什么? 我想將字典轉儲為json字符串。
我正在使用python 2.7
使用此代碼:
import json
fu = {'a':'b'}
output = json.dump(fu)
我收到以下錯誤:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gevent-1.0b2-py2.7-linux-x86_64.egg/gevent/greenlet.py", line 328, in run
result = self._run(*self.args, **self.kwargs)
File "/home/ubuntu/workspace/bitmagister-api/mab.py", line 117, in mabLoop
output = json.dump(fu)
TypeError: dump() takes at least 2 arguments (1 given)
<Greenlet at 0x7f4f3d6eec30: mabLoop> failed with TypeError
使用json.dumps
轉儲str
>>> import json
>>> json.dumps({'a':'b'})
'{"a": "b"}'
json.dump
轉儲到文件
我認為問題是json.dump。 嘗試
json.dumps(fu)
你可以使用json.dumps
。
例:
import json
json.dumps({'zuckerberg':'tech','sachin':'cricket'})
這輸出:
'{"zuckerberg": "tech", "sachin": "cricket"}'
如果你想的按鍵排序,使用sort_keys
作為第二個參數json.dumps
:
json.dumps({'zuckerberg':'tech','sachin':'cricket'},sort_keys=True)
輸出:
'{"sachin": "cricket", "zuckerberg": "tech"}'
message={"message":"Done", "result":"1"} message_json = simplejson.dumps(message) payload = message_json ##or message={"message":"Done", "result":"1"} message_json=jsonify(message)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.