Tampa
Tampa

Reputation: 78244

Python - dump dict as a json string

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

Upvotes: 28

Views: 65201

Answers (4)

Eyasu Tewodros
Eyasu Tewodros

Reputation: 275

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

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

Upvotes: 0

Sharath BJ
Sharath BJ

Reputation: 1473

You can use 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:

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

Outputs:

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

Upvotes: 2

suhailvs
suhailvs

Reputation: 21680

i think the problem is json.dump. try

json.dumps(fu)

Upvotes: 12

jamylak
jamylak

Reputation: 133504

Use json.dumps to dump a str

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

json.dump dumps to a file

Upvotes: 59

Related Questions