[英]Python - dump dict as a json string
What am I missing? 我错过了什么? I want to dump a dictionary as a json string.
我想将字典转储为json字符串。
I am using python 2.7 我正在使用python 2.7
With this code: 使用此代码:
import json
fu = {'a':'b'}
output = json.dump(fu)
I get the following error: 我收到以下错误:
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
Use json.dumps
to dump a str
使用
json.dumps
转储str
>>> import json
>>> json.dumps({'a':'b'})
'{"a": "b"}'
json.dump
dumps to a file json.dump
转储到文件
i think the problem is json.dump. 我认为问题是json.dump。 try
尝试
json.dumps(fu)
You can use json.dumps
. 你可以使用
json.dumps
。
Example: 例:
import json
json.dumps({'zuckerberg':'tech','sachin':'cricket'})
This outputs: 这输出:
'{"zuckerberg": "tech", "sachin": "cricket"}'
If you want to sort the keys, use sort_keys
as the second argument to json.dumps
: 如果你想的按键排序,使用
sort_keys
作为第二个参数json.dumps
:
json.dumps({'zuckerberg':'tech','sachin':'cricket'},sort_keys=True)
Outputs: 输出:
'{"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.