28

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
Stewart Smith
  • 1,396
  • 13
  • 28
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • 1
    @kampu Some research failure but not *severe*, leaving out one letter of a function call is no big deal, maybe just an accident. An attempt and error are showing so according to SO guidelines so it follows the site format. – jamylak Jun 09 '15 at 07:05
  • 7
    My "research" led me here, so this is not a pointless question. Better he ask here and in so doing answer 10,825 viewers' question than leave them wondering where to start to look for the problem. This is why StackOverflow is a thing. RTFM is actually difficult, and often insufficient. – Peter H. Boling Oct 21 '16 at 07:32
  • Possible duplicate of [Converting Dictionary to JSON in python](https://stackoverflow.com/questions/26745519/converting-dictionary-to-json-in-python) – Martin Tapp Oct 16 '18 at 18:36

4 Answers4

59

Use json.dumps to dump a str

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

json.dump dumps to a file

jamylak
  • 128,818
  • 30
  • 231
  • 230
12

i think the problem is json.dump. try

json.dumps(fu)
suhailvs
  • 20,182
  • 14
  • 100
  • 98
2

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"}'
Drenmi
  • 8,492
  • 4
  • 42
  • 51
Sharath BJ
  • 1,393
  • 1
  • 12
  • 16
0
message={"message":"Done", "result":"1"}
message_json = simplejson.dumps(message)
payload = message_json

##or 
message={"message":"Done", "result":"1"}
message_json=jsonify(message)
jamylak
  • 128,818
  • 30
  • 231
  • 230
Eyasu
  • 240
  • 3
  • 13
  • 1
    While this code may solve the question, [including an explanation](//s.tk/meta/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. – 4b0 Apr 17 '19 at 10:49