json to string in Python
Converting JSON to a String in Python
In Python, JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s based on and extends the JavaScript language, representing data in key-value pairs, making it easy for both humans and machines to read and write. The json module of Python can easily convert JSON data and data types in Python.
The JSON data format is as follows:
{
"name": "Tom",
"age": 20,
"score": {
"Chinese": 90,
"Math": 80
},
"hobby": [
"reading",
"running"
]
}
In Python, we can use the json
module to convert JSON data to Python data types, and vice versa. Below, we’ll explain how to convert JSON to a string in Python using example code.
Converting JSON to a String
In Python, you can use the json.dumps()
method to convert Python data types to JSON strings. For example, if we have the following dictionary data:
import json
data = {
"name": "Tom",
"age": 20,
"score": {
"Chinese": 90,
"Math": 80
},
"hobby": [
"reading",
"running"
]
}
json_str = json.dumps(data)
print(json_str)
Running the above code will produce the following output:
{"name": "Tom", "age": 20, "score": {"Chinese": 90, "Math": 80}, "hobby": ["reading", "running"]}
Using the dumps()
method, we can convert data types to JSON. In the result, since we use the dumps method, the key is automatically converted from a “string” to a “double-quoted string”. In addition to the default dumps() method, dumps() has several other methods and parameters:
import json
data = {
“name”: “Tom”,
“age”: 20,
“score”: {
“Chinese”: 90,
“Math”: 80
},
“hobby”: [
“reading”,
“running”
]
}
# The indent parameter is used for formatting the display
json_str1 = json.dumps(data, indent=4)
print(json_str1)
# The separators parameter is used to remove spaces between commas
json_str2 = json.dumps(data, separators=(“,”, “:”))
print(json_str2)
# The sort_keys parameter is used to sort by key value
json_str3 = json.dumps(data, sort_keys=True)
print(json_str3)
The output results are as follows:
{
"name": "Tom",
"age": 20,
"score": {
"Chinese": 90,
"Math": 80
},
"hobby": [
"reading",
"running"
]
}
{"name":"Tom","age":20,"score":{"Chinese":90,"Math":80},"hobby":["reading","running"]}
{"age": 20, "hobby": ["reading", "running"], "name": "Tom", "score": {"Chinese": 90, "Math": 80}}
As shown above, the indent parameter is used to make the JSON string more readable (and it’s useful). By adding a positive integer to this parameter, it indicates the number of key-value pairs in the generated string to wrap. The separators parameter removes spaces from the generated JSON string, removing spaces between commas and colons. The sort_keys parameter is used to sort by key value. These parameters can also be combined, for example:
import json
data = {
"name": "Tom",
"age": 20,
"score": {
"Chinese": 90,
"Math": 80
},
"hobby": [
"reading",
"running"
]
}
json_str = json.dumps(data, indent=4, separators=(",", ": "), sort_keys=True)
print(json_str)
Output:
{
"age": 20,
"hobby": [
"reading",
"running"
],
"name": "Tom",
"score": {
"Chinese": 90,
"Math": 80
}
}
Converting Strings to JSON
In addition to converting Python data types to JSON strings, you can also convert JSON strings to Python data types. Here are two methods: json.loads()
and json.load()
.
The json.loads()
method loads JSON data stored in a string and returns a Python object. For example, if we have the following JSON string:
{
"name": "Tom",
"age": 20,
"score": {
"Chinese": 90,
"Math": 80
},
"hobby": [
"reading",
"running"
]
}
We can use the json.loads()
method to convert it to a Python data type:
import json
json_str = '{"name": "Tom", "age": 20, "score": {"Chinese": 90, "Math": 80}, "hobby": ["reading", "running"]}'
data = json.loads(json_str)
print(data)
Running result:
{'name': 'Tom', 'age': 20, 'score': {'Chinese': 90, 'Math': 80}, 'hobby': ['reading', 'running']}
json.load()
is used to read JSON data from a file and return a Python object. For example, if we have the following JSON file:
{
"name": "Tom",
"age": 20,
"score": {
"Chinese": 90,
"Math": 80
},
"hobby": [
"reading",
"running"
]
}
We can use the json.load()
method to convert it to Python data types:
import json
with open("data.json", "r") as f:
data = json.load(f)
print(data)
The above code reads the data from the file “data.json” and converts it to Python data types. The output is the same as the previous example.
Conclusion
In summary, converting between JSON and strings in Python is straightforward. The json.dumps() , json.loads() , and json.load() methods make this process easy. dumps()
also has other uses, such as writing JSON data to files, which we won’t cover here. I hope this article helps beginners become more familiar with Python’s methods for working with JSON data.