如何使用python修改嵌套的JSON [英] How to modify nested JSON with python
问题描述
我需要使用Python更新(CRUD)嵌套的JSON文件.为了能够整体调用python函数(以更新/删除/创建)并将其写回到json文件中.
I need to update (CRUD) a nested JSON file using Python. To be able to call python function(s)(to update/delete/create) entires and write it back to the json file.
这是一个示例文件.
我正在查看 remap 库,但是不知道这是否行得通.
I am looking at the remap library but not sure if this will work.
{
"groups": [
{
"name": "group1",
"properties": [
{
"name": "Test-Key-String",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
},
{
"name": "Test-Key-Integer",
"value": {
"type": "Integer",
"data": 1000
}
}
],
"groups": [
{
"name": "group-child",
"properties": [
{
"name": "Test-Key-String",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
},
{
"name": "Test-Key-Integer",
"value": {
"type": "Integer",
"data": 1000
}
}
]
}
]
},
{
"name": "group2",
"properties": [
{
"name": "Test-Key2-String",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value2"
}
}
]
}
]
}
推荐答案
我觉得我在您的问题中遗漏了一些东西.无论如何,据我了解,您想读取一个json文件,将数据编辑为python对象,然后将其与更新后的数据一起写回去吗?
I feel like I'm missing something in your question. In any event, what I understand is that you want to read a json file, edit the data as a python object, then write it back out with the updated data?
读取json文件:
import json
f = open("data.json")
raw_data = f.read()
f.close()
data = json.loads(raw_data)
这将创建一个字典(给定格式),您可以根据需要操作它.假设您要写出来:
That creates a dictionary (given the format you've given) that you can manipulate however you want. Assuming you want to write it out:
json_data = json.dumps(data)
f = open("data.json","w")
f.write(json_data)
f.close()
这篇关于如何使用python修改嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!