python - 使用 Python 更新 JSON 文件中的值

标签 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)

最佳答案

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
                }
            ]
        }
    ]
}

看起来订单也被保留了,尽管我不能说这是否是一个保证,因为我以前从未关注过这种行为

关于python - 使用 Python 更新 JSON 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55944134/

相关文章:

python - 如何从Python字典中打印2个键

在点后添加空格的Python正则表达式

python - 我应该如何 JSON 序列化 Enum-children?

iOS JSON 解析错误

sql - 将 JSON 转换为基于 Presto 的 SQL 查询

android - 如何解析JSON对象中的多个JSON对象?

python - 如何浏览到带有绘图破折号的文件夹?

python - Django 表单如何清理文本输入以防止 SQL 注入(inject)、XSS 等?

python - 从缺失值大于 5 的行中删除缺失值,然后打印每列中缺失值的百分比

javascript - d3中基于日期的JSON解析