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

PythonJson

Python Problem Overview


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

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

Python Solutions


Solution 1 - Python

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())

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnMareeView Question on Stackoverflow
Solution 1 - PythonchepnerView Answer on Stackoverflow
Solution 2 - Pythonstackhelper101View Answer on Stackoverflow