Python中的JSON处理函数:10个示例
JSON是JavaScript对象表示法的缩写,它是一种轻量级的数据交换格式,易于阅读和编写。Python提供了许多处理JSON数据的方法和函数,这些方法和函数可以方便地处理JSON格式的数据。 在本文中,我们将介绍Python中处理JSON数据的10个示例。
1. 使用json模块的dumps()函数将Python对象序列化为JSON格式的字符串:
import json
person = {"name": "John Doe", "age": 40, "city": "New York"}
# Serialize the Python object into a JSON string
json_string = json.dumps(person)
print(json_string)
输出:
{"name": "John Doe", "age": 40, "city": "New York"}
2. 使用dump()函数将Python对象序列化为JSON格式的文件
# Create a Python object
person = {"name": "John Doe", "age": 40, "city": "New York"}
# Open a file for writing
with open("person.json", "w") as f:
# Serialize the Python object to a JSON format and write to the file
json.dump(person, f)
3. 使用load()函数将JSON格式的文件反序列化为Python对象:
# Open a file for reading
with open("person.json", "r") as f:
# Deserialize the JSON data into a Python object
person = json.load(f)
print(person)
输出:
{'name': 'John Doe', 'age': 40, 'city': 'New York'}
4. 使用loads()函数将JSON格式的字符串反序列化为Python对象:
# A JSON string
json_string = '{"name": "John Doe", "age": 40, "city": "New York"}'
# Deserialize the JSON string into a Python object
person = json.loads(json_string)
print(person)
输出:
{'name': 'John Doe', 'age': 40, 'city': 'New York'}
5. 将Python对象转换为JSON格式,但指定缩进:
# Create a Python object
person = {"name": "John Doe", "age": 40, "city": "New York"}
# Serialize the Python object to a JSON format with indention of 4 spaces
json_string = json.dumps(person, indent=4)
print(json_string)
输出:
{
"name": "John Doe",
"age": 40,
"city": "New York"
}
6. 将Python对象转换为JSON格式,但去掉空格:
# Create a Python object
person = {"name": "John Doe", "age": 40, "city": "New York"}
# Serialize the Python object to a JSON format without spaces
json_string = json.dumps(person, separators=(",", ":"))
print(json_string)
输出:
{"name":"John Doe","age":40,"city":"New York"}
7. 使用default()函数自定义对象的序列化:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
person = Person("John Doe", 40)
json_string = person.toJSON()
print(json_string)
输出:
{
"age": 40,
"name": "John Doe"
}
8. 使用object_hook()函数自定义对象的反序列化:
def decode_person(dct):
if "__class__" in dct and dct["__class__"] == "Person":
return Person(dct["name"], dct["age"])
return dct
# A JSON string that represents a Python object of type Person
json_string = '{"__class__": "Person", "name": "John Doe", "age": 40}'
# Deserialize the JSON string using the custom decoding function
person = json.loads(json_string, object_hook=decode_person)
print(person)
输出:
<__main__.Person instance at 0x000001>
9. 将类的实例使用JSON进行深度复制:
# Create a Python object
person1 = {"name": "John Doe", "age": 40, "city": "New York"}
# Use the copy module to make a deep copy
import copy
person2 = copy.deepcopy(person1)
# Serialize the Python object to a JSON format
json_string = json.dumps(person1)
# Deserialize the JSON object into a new Python object
person3 = json.loads(json_string)
print(person2)
print(person3)
输出:
{'name': 'John Doe', 'age': 40, 'city': 'New York'}
{'name': 'John Doe', 'age': 40, 'city': 'New York'}
10. 在Python中使用JSON Schema验证JSON对象:
import jsonschema
# Create the JSON Schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
}
# A Python object that we want to validate against the schema
person = {"name": "John Doe", "age": 40}
# Validate the Python object against the schema
jsonschema.validate(person, schema)
print("The object is valid according to the schema")
输出:
The object is valid according to the schema
以上就是Python中JSON处理函数的10个示例。这些函数可以非常方便地处理JSON格式的数据,并帮助我们有效地进行JSON数据的序列化和反序列化;还可以对JSON进行验证和操作。掌握它们将有助于我们更好地处理JSON格式数据。
