简体   繁体   English

如何从 JSON 文件中删除键/对象?

[英]How to remove a key/object from a JSON file?

I want to go into the JSON file and find "class": "DepictionScreenshotsView", and remove it completely or change it to "class": "", I been at this for hours with no luck I already tried Googling but nothing so any help will be welcome!我想进入 JSON 文件并找到"class": "DepictionScreenshotsView",然后将其完全删除或将其更改为"class": "",我已经在这里呆了几个小时但没有运气我已经尝试过谷歌搜索,但什么也没有欢迎帮助!

Edit: We are looking at elif new_url == "" if that's helpful.编辑:如果有帮助,我们正在查看elif new_url == ""

Code:代码:

#!/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 File: 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
            }
         ]
      }
   ]
}

Easier to read the data into a dict then traverse this and remove offending keys更容易将数据读入 dict 然后遍历它并删除有问题的键

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)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM