2 回答

TA贡献1893条经验 获得超10个赞
以下代码将打开您的 JSON 文件并将 JSON 结构读取到变量中data。
然后它将创建list.copy(data['tabs'][0]['views'])结构的副本(data['tabs'][0]['views']指的是组索引 0 的“视图”部分,或list在 Python 术语中,“选项卡”部分),在这种情况下,这是您要定位的结构,如变量new_tab。
接下来,它会在每个视图value的“标题”或“降价”key中添加一个空格和“复制”一词,具体取决于new_tab(副本)中存在哪个视图。
然后它会添加new_tab到现有的 JSON 结构中。
最后,它将更新后的 JSON 结构写入原始文件。
with open(filename, 'r') as copying:
data = json.load(copying)
new_tab = list.copy(data['tabs'][0]['views'])
for view in new_tab:
if 'title' in view.keys():
view['title'] = f"{view['title']} copy"
elif 'markdown' in view.keys():
view['markdown'] = f"{view['markdown']} copy"
data['tabs'][0]['views'].extend(new_tab)
with open(filename, 'w') as copying:
json.dump(data, copying)
输出将是一个如下所示的文件:
{
"minVersion": "0.1",
"headerImage": "",
"tintColor": "",
"tabs": [
{
"tabname": "Changelog",
"views": [
{
"title": "1.0 copy",
"useBoldText": true,
"useBottomMargin": true,
"class": "DepictionSubheaderView"
},
{
"markdown": "\t\n• Initial Release copy",
"useSpacing": false,
"class": "DepictionMarkdownView"
},
{
"markdown": "<small style=\"color: #999; margin-top: -8px;\">Released 3/7/2019</small> copy",
"useRawFormat": true,
"class": "DepictionMarkdownView"
},
{
"title": "1.0 copy",
"useBoldText": true,
"useBottomMargin": true,
"class": "DepictionSubheaderView"
},
{
"markdown": "\t\n• Initial Release copy",
"useSpacing": false,
"class": "DepictionMarkdownView"
},
{
"markdown": "<small style=\"color: #999; margin-top: -8px;\">Released 3/7/2019</small> copy",
"useRawFormat": true,
"class": "DepictionMarkdownView"
}
],
"class": "DepictionStackView"
}
],
"class": "DepictionTabView"
}
附带说明一下,每当您使用 JSON 时,最好测试一下您的结构。在JSONLint 上有一个很好的资源可以做到这一点 - JSON 验证器只需复制您的 JSON 结构,将其粘贴到那里,然后单击“验证 JSON”按钮。

TA贡献1818条经验 获得超8个赞
你阅读你的 JSON 文件,选择你需要的部分,然后把你想要的放在文件的开头。假设您的文件名为data.json:
import json
with open('data.json') as f:
data = json.load(f)
required_data = data["tabs"][0]["views"]
f.seek(0, 0)
f.write(str(required_data) + '\n' + str(data))
添加回答
举报