我想进入JSON文件并找到"class": "DepictionScreenshotsView",
并将其完全删除或将其更改为"class": "",
我已经花了几个小时没有运气,我已经尝试了谷歌搜索,但是没有任何帮助,因此不客气!
编辑:如果有帮助,我们正在研究elif new_url == ""
。
代码:
#!/usr/bin/env python3
import os
# Load the data
file_name = "path/to/json/file"
with open(file_name) as fh:
full_data = json.load(fh)
screen_shots = full_data['tabs'][0]['views'][3]['screenshots']
for number, screen_shot in enumerate(screen_shots):
new_url = input("Screnshot URL: ").strip()
if new_url:
screen_shot.update({"url": new_url, "fullSizeURL": new_url})
elif new_url == "":
#for k, v in full_data.items():
# if isinstance(v, dict) and v.get("class") == "DepictionScreenshotsView":
# full_data.pop(k)
# break
#json_lines = []
#for line in fh.readlines():
# j = json.loads(line)
# if not j['class'] == 'DepictionScreenshotsView':
# json_lines.append(line)
full_data['tabs'][0]['views'][3]['screenshots'] = screen_shots
full_data['tabs'][0]['views'][3]['class'] = screen_shots
else:
break
with open(file_name, 'w') as fh:
json.dump(full_data, fh, indent=4)
JSON文件:
{
"minVersion": "0.1",
"class": "DepictionTabView",
"tintColor": "#2cb1be",
"headerImage": "",
"tabs": [
{
"tabname": "Details",
"class": "DepictionStackView",
"tintColor": "#2cb1be",
"views": [
{
"class": "DepictionSubheaderView",
"useBoldText": true,
"useBottomMargin": false,
"title": "Description"
},
{
"class": "DepictionMarkdownView",
"markdown": "Some dummy text...",
"useRawFormat": true
},
{
"class": "DepictionSeparatorView"
},
{
"class": "DepictionSubheaderView",
"useBoldText": true,
"useBottomMargin": false,
"title": "Screenshots"
},
{
"class": "DepictionScreenshotsView",
"itemCornerRadius": 6,
"itemSize": "{160, 284.44444444444}",
"screenshots": [
{
"accessibilityText": "Screenshot",
"url": "http://example.com/image.png"
}
]
},
{
"class": "DepictionSeparatorView"
},
{
"class": "DepictionSubheaderView",
"useBoldText": true,
"useBottomMargin": false,
"title": "Information"
},
{
"class": "DepictionTableTextView",
"title": "Author",
"text": "User"
},
{
"class": "DepictionSpacerView",
"spacing": 16
},
{
"class": "DepictionStackView",
"views": [
{
"class": "DepictionTableButtonView",
"title": "Contact",
"action": "http://example.com/",
"openExternal": true
}
]
},
{
"class": "DepictionSpacerView",
"spacing": 16
}
]
},
{
"tabname": "History",
"class": "DepictionStackView",
"views": [
{
"class": "DepictionSubheaderView",
"useBoldText": true,
"useBottomMargin": false,
"title": ""
},
{
"class": "DepictionMarkdownView",
"markdown": "<ul>\n<li>Initial release.<\/li>\n<\/ul>",
"useRawFormat": true
}
]
}
]
}
答案 0 :(得分:1)
更容易将数据读取到字典中,然后遍历并删除有问题的键
import os
import json
file_name = "/tmp/jsonfile.json"
with open(file_name) as fh:
full_data = json.load(fh)
fh.close()
for tab in full_data['tabs']:
for view in tab['views']:
if view['class'] == 'DepictionScreenshotsView':
del view['class']
if 'screenshots' in view:
view['screenshots'] = []
print json.dumps(full_data)