深度阅读

How to modify a key-value pair in a JSON object in Python?

作者
作者
2023年08月22日
更新时间
9.1 分钟
阅读时间
0
阅读量

To modify a key-value pair in a JSON object in Python, you need to first parse the JSON data into a Python object using the json module’s loads() method. You can then modify the desired key-value pair using dictionary-style indexing, and then convert the modified Python object back into JSON format using the json module’s dumps() method.

Here’s an example:

import json

# Example JSON data
json_str = '{"name": "John", "age": 30, "city": "New York"}'

# Parse JSON data into Python object
data = json.loads(json_str)

# Modify a key-value pair
data["age"] = 40

# Convert modified Python object back into JSON format
json_str_modified = json.dumps(data)

# Print the modified JSON data
print(json_str_modified)

This will output:

{"name": "John", "age": 40, "city": "New York"}

As you can see, the age key-value pair has been modified to have a value of 40 instead of 30.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。