Hello folks! I recently started my Python journey and came across Python's JSON module while working on a project. I encountered two functions : json.load()
and json.loads()
which look similar and hence confused me a lot. After some research and playing around with the two functions, I finally got a clear idea. So I thought of sharing my learnings regarding it in today's article.
What's common in them?
Both json.load()
and json.loads()
are used to parse JSON data and convert it into corresponding Python objects. Now, let's talk about the differences between them.
What does json.load() do?
The json.load()
function loads data from a file like object (.txt file or .json file) and converts it into a python object.
Let's understand this by an example.
Suppose we have data in JSON format which looks like this (image above).
And this (image above) is our python script. We have opened a file name data.json in reading mode and are loading it's data into a variable named loaded_data using the json.load()
function. Here json.load()
function is being used to load json data from the data.json file. Remember this point : json.load()
for loading data from a file like object. Because this is the point where it differs from the json.loads()
function.
Now let's look at the output.
We got a list as output (image above). If we have an array of objects as data then we'll get a list as output, if we have a single object as data then we'll get a dictionary as output.
Now let's talk about json.loads()
method.
What does json.loads() do?
The json.loads()
function parses a json string into a python object. And this is the point of difference! json.load()
reads JSON data from a file like object but json.loads()
parses a json string into a python object.
Let's understand this with an example.
Suppose we have a variable named string_data (image above) that contains our JSON string. Now we want to load that JSON string into a variable as a python object, so we'll have to use the json.loads()
function.
Now let's look at the output.
We got a python list as the output (image above). For json.loads()
too, if we have a single object in the JSON string then we'll get a python dictionary as output, and if we have an array of object in the JSON string then we'll get python list as output.
Summary
Both, json.load()
and json.loads()
, convert JSON data into Python objects. json.load()
reads JSON data from a file-like object and converts it into a Python object, while json.loads()
parses a JSON string into a Python object.
Hope you found this article on json.load()
vs json.loads()
helpful. Happy coding😄!