Trusted answers to developer questions

What is the difference between json.loads() and json.dumps()?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

The JSON objects are surrounded by curly braces { }. They are written in key and value pairs. In this Answer, we will discuss the difference between the json.loads() and the json.dumps().

The json.loads() takes in a string and returns a python object and the json.dumps() takes in a Python object and returns a JSON string.

As we can see, json.dumps() and json.loads() are opposite of one another.

The json.loads() example

In this example, a string is converted into a Python object, and the key age is accessed in that object:

import json
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])

In this case, it converts the JSON string into a Python dictionary, because the JSON string represents an object with key-value pairs.

The json.dumps() example

In this example, a json object is passed in the json.dumps() function, and its data is extracted and returned in the form of a string:

import json
a = {'lalalala': 3}
myString = json.dumps(a)
print (myString)

In summary, json.loads() converts JSON strings to Python objects, while json.dumps() converts Python objects to JSON strings. These functions are essential for handling JSON data within Python scripts, facilitating easy conversion and manipulation of structured data.

RELATED TAGS

json.dumps
json.loads
difference
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?