使用Python更新JSON文件中的值

时间:2019-05-02 00:07:04

标签: python json

如何输入json文件并找到"class": "DepictionScreenshotsView"并将其替换为"class": ""?任何帮助都将受到欢迎。

代码/我尝试过的事情:

#!/usr/bin/env python3
import json

# 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()

    str = """{
        "class" : "DepictionScreenshotsView"
    }"""
    data = json.loads(str)
    data["class"] = "test"

    full_data['tabs'][0]['views'][3]['screenshots'] = screen_shots

with open(file_name, 'w') as fh:
    json.dump(full_data, fh, indent=4)

JSON文件:

{
   "minVersion": "1",
   "class": "DepictionTabView",
   "tintColor": "",
   "headerImage": "",
   "tabs": [
      {
         "tabname": "Details",
         "class": "DepictionStackView",
         "tintColor": "",
         "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": "",
               "useRawFormat": true
            }
         ]
      }
   ]
}

编辑:我也尝试了这段代码,但是没有运气(顺便说一下,这只是我的代码的一部分,而不是完整的代码)

import json

# Load the data
file_name = "path/to/json/file"
with open(file_name) as fh:
    full_data = json.load(fh)

    for tab in full_data.get('tabs', []):
        for view in full_data.get('views', []):
            if view.get('class') == 'DepictionScreenshotsView':
                view['class'] = ''

with open(file_name, 'w') as fh:
    json.dump(full_data, fh, indent=4)

1 个答案:

答案 0 :(得分:0)

IIUC,您应该能够循环访问嵌套元素以找到所需内容:

import json

with open("/path/to/file.json") as fh:
    content = json.load(fh)

# The second arg in get is the return in case the key isn't there
# and returning empty list will prevent errors saying NoneType isn't iterable
for tab in content.get('tabs', []):
    for view in content.get('views', []):
        if view.get('class') == 'DepictionScreenshotsView':
            view['class'] = ''

# This modifies content in place

with open('/path/to/newfile.json', 'w') as fh:
    json.dump(content, fh, indent=4)

哪个会给:

{
    "minVersion": "1",
    "class": "DepictionTabView",
    "tintColor": "",
    "headerImage": "",
    "tabs": [
        {
            "tabname": "Details",
            "class": "DepictionStackView",
            "tintColor": "",
            "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": "",
                    "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": "",
                    "useRawFormat": true
                }
            ]
        }
    ]
}

看起来也保留了顺序,尽管我不能说这是否可以保证,因为我以前从没注意过这种行为