JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
In Python, JSON can be handled using the json module. The json module provides two methods for working with JSON: json.dumps() and json.loads(). Both methods are used to convert between Python objects and JSON.
json.dumps() method:
The json.dumps() method is used to convert a Python object into a JSON string. The method takes an object and returns a JSON string representation of the object.
For example:
import json
data = {
"name": "John Smith",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
This will output the following JSON string:
{"name": "John Smith", "age": 30, "city": "New York"}
json.loads() method:
The json.loads() method is used to convert a JSON string into a Python object. The method takes a JSON string and returns a Python object.
For example:
import json
json_data = '{"name": "John Smith", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data)
This will output the following Python object:
{'name': 'John Smith', 'age': 30, 'city': 'New York'}
In conclusion, json.dumps() method is used to convert a Python object into a JSON string, while json.loads() method is used to convert a JSON string into a Python object. These two methods are essential for working with JSON data in Python.
Additional options for json.dumps():
json.dumps() method also provides several options for customizing the output. Some of the most commonly used options are:
- indent: This option is used to specify the number of spaces to use for indentation. If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. Using indent option, you can make the output more readable.
For example:
json_data = json.dumps(data, indent=4)
print(json_data)
This will output the following JSON string:
{
"name": "John Smith",
"age": 30,
"city": "New York"
}
- separators: This option is used to specify the separator to use between items. The default separator is (',', ':')
For example:
json_data = json.dumps(data, separators=(',', ':'))
print(json_data)
This will output the following JSON string:
{"name":"John Smith","age":30,"city":"New York"}
- sort_keys: This option is used to specify whether the output should be sorted by key. The default value is False
For example:
json_data = json.dumps(data, sort_keys=True)
print(json_data)
This will output the following JSON string:
{"age": 30, "city": "New York", "name": "John Smith"}
Additional options for json.loads():
json.loads() method also provides several options for customizing the input. Some of the most commonly used options are:
- object_hook: This option is used to specify a function that will be called with the result of any object literal decoded
For example:
def json_object_hook(dct):
if 'name' in dct:
dct['name'] = dct['name'].upper()
return dct
data = json.loads(json_data, object_hook=json_object_hook)
print(data)
This will output the following Python object:
{'name': 'JOHN SMITH', 'age': 30, 'city': 'New York'}
- object_pairs_hook: This option is used to specify a function that will be called with the result of any object literal decoded with an ordered list of pairs.
For example:
def json_object_pairs_hook(pairs):
d = {}
for key, value in pairs:
if key in d:
d[key].append(value)
else:
d[key] = [value]
return d
data = json.loads(json_data, object_pairs_hook=json_object_pairs_hook)
print(data)
This will output the following Python object:
{'name': ['John Smith'], 'age': [30], 'city': ['New York']}
Popular questions
- What is the difference between json.dumps() and json.loads() in Python?
- json.dumps() is used to convert a Python object into a JSON string, while json.loads() is used to convert a JSON string into a Python object.
- How do you use json.dumps() in Python?
- The json.dumps() method is used to convert a Python object into a JSON string. The method takes an object and returns a JSON string representation of the object. For example:
import json
data = {
"name": "John Smith",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
- How do you use json.loads() in Python?
- The json.loads() method is used to convert a JSON string into a Python object. The method takes a JSON string and returns a Python object. For example:
import json
json_data = '{"name": "John Smith", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data)
- What is the use of the indent option in json.dumps()?
- The indent option is used to specify the number of spaces to use for indentation. If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. This option can make the output more readable.
- Can you give an example of using object_hook option in json.loads()?
- The object_hook option is used to specify a function that will be called with the result of any object literal decoded. This can be useful for customizing the output. For example:
def json_object_hook(dct):
if 'name' in dct:
dct['name'] = dct['name'].upper()
return dct
json_data = '{"name": "John Smith", "age": 30, "city": "New York"}'
data = json.loads(json_data, object_hook=json_object_hook)
print(data)
This will output the following Python object:
{'name': 'JOHN SMITH', 'age': 30, 'city': 'New York'}
Tag
Serialization