167

What is the difference between json.dumps and json.load?

From my understanding, one loads JSON into a dictionary and another loads into objects.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
AnMaree
  • 1,771
  • 2
  • 12
  • 11

2 Answers2

223

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    This is very helpful for my understanding. Still I'm a little confused as I thought everything is an object in Python. Wouldn't string be an object in itself? How could you convert between the two then? Sorry for the silly question. – Bowen Liu Aug 21 '18 at 18:52
  • 1
    I'm using `object` in the sense of "something of a type other than `str`". A string like `'"foo"'` is decoded to the *Python* `str` object `'foo'`; a string like `"[1,2,3]"` is decoded to the Python list `[1,2,3]`, etc. – chepner Sep 04 '19 at 12:13
  • 1
    `dumps()`- encoding to JSON objects `dump()`- encoded string writing on file `loads()`- Decode the JSON string `load()`- Decode while JSON file read – Jamil Noyda Apr 16 '20 at 08:30
97

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

stackhelper101
  • 1,019
  • 6
  • 5
  • 11
    > json dumps -> returns a string representing a json object from a dict. That's close, but it doesn't have to be a dict you pass in to json.dumps(). You can pass a list, or a string, or a boolean.. – Ross Oct 02 '15 at 16:10