Python - 将 dict 转储为 json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16668511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:18:42  来源:igfitidea点击:

Python - dump dict as a json string

pythonjson

提问by Tampa

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

采纳答案by jamylak

Use json.dumpsto dump a str

使用json.dumps转储str

>>> import json
>>> json.dumps({'a':'b'})
'{"a": "b"}'

json.dumpdumps to a file

json.dump转储到文件

回答by suhailvs

i think the problem is json.dump. try

我认为问题是 json.dump。尝试

json.dumps(fu)

回答by Sharath BJ

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_keysas the second argument to json.dumps:

如果要对键进行排序,请sort_keys用作第二个参数json.dumps

json.dumps({'zuckerberg':'tech','sachin':'cricket'},sort_keys=True)

Outputs:

输出:

'{"sachin": "cricket", "zuckerberg": "tech"}'

回答by Eyasu

message={"message":"Done", "result":"1"}
message_json = simplejson.dumps(message)
payload = message_json

##or 
message={"message":"Done", "result":"1"}
message_json=jsonify(message)