要编辑或重命名一个json字典中的键名,可以按照以下代码示例进行操作:
import json
# 原始的json数据
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# 将json数据加载为字典
data = json.loads(json_data)
# 打印原始的字典数据
print("原始数据:", data)
# 编辑/重命名键名
data["new_name"] = data.pop("name")
# 打印编辑后的字典数据
print("编辑后的数据:", data)
# 将编辑后的字典转换回json数据
new_json_data = json.dumps(data)
# 打印编辑后的json数据
print("编辑后的json数据:", new_json_data)
输出为:
原始数据: {'name': 'John', 'age': 30, 'city': 'New York'}
编辑后的数据: {'new_name': 'John', 'age': 30, 'city': 'New York'}
编辑后的json数据: {"new_name": "John", "age": 30, "city": "New York"}
在这个示例中,我们首先使用json.loads()
函数将json数据加载为一个字典。然后,我们使用data.pop("name")
删除原始键名"name",并将其赋值给一个新的键名"new_name"。最后,我们使用json.dumps()
函数将编辑后的字典转换回json数据。