【问题标题】:Python - Deleting Lines of Code In JSON FilePython - 删除 JSON 文件中的代码行
【发布时间】:2019-03-11 04:38:33
【问题描述】:

我想搜索并替换 JSON 文件的多行代码,除了第一个将使用用户输入的代码外,我无法让它工作 我想搜索 JSON 文件并找到我正在寻找的代码for 并删除它或将其替换为空。

我想删除我的 JSON 文件中的所有内容,例如里面的内容以及 { 和结束的 }, 标记。

代码:

screenshoturl = input("Screenshot URL 1: ")

# Search JSON file for the placeholders and replace them with nothing.
removescreenshotsplaceholders = {
  'Screenshot URL 1':screenshoturl,
  '''{
  "accessibilityText": "Screenshot",
  "url": "Screenshot URL 2",
  "fullSizeURL": "Screenshot URL 2"
  },''':'',
  '''{
  "accessibilityText": "Screenshot",
  "url": "Screenshot URL 3",
  "fullSizeURL": "Screenshot URL 3"
  },''':'',
  '''{
  "accessibilityText": "Screenshot",
  "url": "Screenshot URL 4",
  "fullSizeURL": "Screenshot URL 4"
  },''':'',
  '''{
  "accessibilityText": "Screenshot",
  "url": "Screenshot URL 5",
  "fullSizeURL": "Screenshot URL 5"
  }''':''
  }

  with open('path/to/json/file') as infile, open(/path/to/to/save/copy, 'w') as outfile:
      for removescreenshots in infile:
          for screenshot, removescreenshot in removescreenshotsplaceholders.items():
              removescreenshots = removescreenshots.replace(screenshot, removescreenshot)
          outfile.write(removescreenshots)

这是我希望脚本在 JSON 文件中搜索并删除它的内容:

'''{
      "accessibilityText": "Screenshot",
      "url": "Screenshot URL 2",
      "fullSizeURL": "Screenshot URL 2"
      },''':'',
      '''{
      "accessibilityText": "Screenshot",
      "url": "Screenshot URL 3",
      "fullSizeURL": "Screenshot URL 3"
      },''':'',
      '''{
      "accessibilityText": "Screenshot",
      "url": "Screenshot URL 4",
      "fullSizeURL": "Screenshot URL 4"
      },''':'',
      '''{
      "accessibilityText": "Screenshot",
      "url": "Screenshot URL 5",
      "fullSizeURL": "Screenshot URL 5"
      }''':''

JSON 文件:

{
  "tabs": [
    {
      "tabname": "Details",
      "views": [
        {
          "title": "Some Name",
          "useBoldText": true,
          "useBottomMargin": false,
          "class": "DepictionSubheaderView"
        },
        {
          "itemCornerRadius": 6,
          "itemSize": "",
          "screenshots": [
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 1",
              "fullSizeURL": "Screenshot URL 1"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 2",
              "fullSizeURL": "Screenshot URL 2"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 3",
              "fullSizeURL": "Screenshot URL 3"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 4",
              "fullSizeURL": "Screenshot URL 4"
            },
            {
              "accessibilityText": "Screenshot",
              "url": "Screenshot URL 5",
              "fullSizeURL": "Screenshot URL 5"
            }
          ],
          "ipad": {
            "itemCornerRadius": 9,
            "itemSize": "{320, 550.8266666666667}",
            "screenshots": [
              {
                "accessibilityText": "Screenshot",
                "url": " Screenshot URL?size=640",
                "fullSizeURL": "Screenshot URL"
              }
            ],
            "class": "DepictionScreenshotView"
          },
          "class": "DepictionScreenshotsView"
        },
        {
          "markdown": " Description",
          "useSpacing": true,
          "class": "DepictionMarkdownView"
        },
        {
          "class": "DepictionSeparatorView"
        },
        {
          "title": "Known Issues",
          "class": "DepictionHeaderView"
        },
        {
          "markdown": "None",
          "useSpacing": true,
          "class": "DepictionMarkdownView"
        },
        {
          "class": "DepictionSeparatorView"
        },
        {
          "title": "Latest Version",
          "class": "DepictionHeaderView"
        },
        {
          "title": "1.0",
          "text": "Latest Version Number",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Released",
          "text": "3/10/19",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Price",
          "text": "Free",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Developer",
          "text": "TestDev",
          "class": "DepictionTableTextView"
        },
        {
          "title": "Contact Support",
          "action": "",
          "class": "DepictionTableButtonView"
        },
        {
          "spacing": 16,
          "class": "DepictionSpacerView"
        },
        {
          "spacing": 20,
          "class": "DepictionSpacerView"
        }
      ],
      "class": "DepictionStackView"
    },
    {
      "tabname": "Changelog",
      "views": [
        {
          "title": "1.0",
          "useBoldText": true,
          "useBottomMargin": true,
          "class": "DepictionSubheaderView"
        },
        {
          "markdown": "\t\n\u2022 Initial Release",
          "useSpacing": false,
          "class": "DepictionMarkdownView"
        },
        {
          "markdown": "<small style=\"color: #999; margin-top: -8px;\">Released 3/10/2019</small>",
          "useRawFormat": true,
          "class": "DepictionMarkdownView"
        }
      ],
      "class": "DepictionStackView"
    }
  ],
  "class": "DepictionTabView"
}

我尝试了使用和不使用''' 并尝试弄乱输入和输出文件以及其他一些东西似乎没有任何作用,因此欢迎任何帮助。

谢谢!

【问题讨论】:

  • 你已经尝试了什么?
  • 我尝试了使用和不使用''' 并尝试弄乱输入和输出文件以及其他一些东西似乎没有任何效果。
  • 如果行尾有逗号或左括号,则不需要使用三引号。或者,您可以在行尾使用连接字符,这是一个 `\` 字符。该字符,如果在 Python 代码中位于行尾,则表示将关联以下行。
  • 作为一个建议,而不是将其视为 json 和字符串问题,您可能会更好地解析 json,并使用实际的 python 字典,然后将 dict 重写为json 删除了正确的元素。当你可以解析它时,不要使用原始的 json 字符串。
  • 抱歉,我对 Python 很陌生,我不知道该怎么做@Paritosh Singh,但谢谢。

标签: python json


【解决方案1】:

这有点复杂。您的 JSON 文件格式包含许多 &lt;list&gt; 数据(根据 Python 解释)。我给你写了一个快速简单的解决方案 - 请参阅下面的源代码。但是,它希望改进自定义解析器的代码,或者改进从 JSON 到 Python 的转换,反之亦然。您还可以将 OOP 代码截断为一行,例如:data = json.loads(open('/tmp/a.json','r').read())。但是您写道,您对 Python 还是很陌生。因此,在多行上,更好地理解。通过 Python 控制台进行测试,否则必须将所有变量粘贴到 print()

import json

### read json data from file
#with open('/tmp/a.json') as f:
#    data = json.load(f)

### read text from file
with open('/tmp/a.json','r') as f:
    data = f.read()

### decode JSON data
data = json.loads(data)

print('- check before:')
data['tabs'][0]['views'][1]['screenshots']

print('- Now we\'re going to overwrite the whole frame with "screenshots" for one, the first one that\'s already there. So there will only be the first record, i.e. "Screenshot URL 1" as you like.')
data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0] 

print('- check after:')
data['tabs'][0]['views'][1]['screenshots']

### write encoded JSON data to output file
### warning - the tree structure will be deleted (all newlines), but the JSON format should remain original
with open('/tmp/b.json','w') as f:
    f.write(json.dumps(data))

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2020-12-15
    • 2017-12-01
    • 2020-09-05
    • 2021-05-11
    相关资源
    最近更新 更多