When working with JSON data in Python, two functions often come into play: json.loads() and json.dumps(). These methods are essential for converting between JSON strings and Python objects, but they serve different purposes.
Let's start with json.loads(). This function is designed to take a string representation of a JSON object—think of it as the text version you might see when inspecting an API response—and convert it into a corresponding Python dictionary. For instance, if you have a string like this:
json_str = '{"token":"abc123", "status":0, "data":{"name":"admin", "password":123456}, "author":null}'
Using json.loads(json_str) will transform that string into something more usable within your code:
{'token': 'abc123', 'status': 0, 'data': {'name': 'admin', 'password': 123456}, 'author': None}
This transformation allows you to access values using keys just like any other dictionary.
On the flip side is json.dumps(), which does the opposite. It takes a Python object (like our newly created dictionary) and converts it back into a JSON-formatted string. This can be particularly useful when you're preparing data to send over an API or save to a file. Here's how you'd use it:
dict_data = {'token': 'abc123', 'status': 0, 'data': {'name':'admin', 'password':'secret'}, 'author': None}
jstr = json.dumps(dict_data)
print(jstr)
The output would look something like this:
{"token": "abc123", "status": 0, "data": {"name": "admin", "password": "secret"}, "author": null}
you'll notice that all keys are now wrapped in double quotes—a requirement for valid JSON.
both functions allow for additional parameters such as custom serialization options or pretty-printing through indentation settings.
in summary,
n`loads()` is perfect for reading incoming JSON strings from APIs or files and turning them into dictionaries,
and `dumps()` shines when it's time to serialize those dictionaries back into readable JSON format.
