Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - dump dict as a json string

Tags:

python

json

What am I missing? I want to dump a dictionary as a json string.

I am using 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 
like image 442
Tampa Avatar asked May 21 '13 11:05

Tampa


People also ask

How do I export a dictionary to a JSON in Python?

1) Using dumps() function Python possesses a default module, 'json,' with an in-built function named dumps() to convert the dictionary into a JSON object by importing the "json" module. "json" module makes it easy to parse the JSON strings which contain the JSON object.

Can dictionary be converted to JSON?

To Convert dictionary to JSON you can use the json. dumps() which converts a dictionary to str object, not a json(dict) object! so you have to load your str into a dict to use it by using json.

Which method is used to convert a dictionary to JSON string?

dumps() method: This method is used to convert the dictionary object into JSON data for parsing or reading and it is slower than dump() method.


1 Answers

Use json.dumps to dump a str

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

json.dump dumps to a file

like image 198
jamylak Avatar answered Sep 24 '22 17:09

jamylak