Python-删除JSON文件中的代码行 [英] Python - Deleting Lines of Code In JSON File

查看:102
本文介绍了Python-删除JSON文件中的代码行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to search and replace multiple lines of code a JSON file with nothing except the first one that will use the users input but I cant get it to work I would like to search a JSON file and find the code im looking for and remove it or replace it with nothing.

我想删除JSON文件中的所有内容,例如内部的内容以及{和结尾}标签.

I want to delete everything like the stuff inside and the { and the closing }, tag in my JSON file.

代码:

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文件中搜索并将其删除的内容:

This is what I want the script to search for in the JSON file and remove it:

'''{
      "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"
}

我尝试了使用'''和不使用'''的情况,并尝试弄乱了in和out文件以及其他一些东西,但似乎没有任何效果,因此欢迎您提供任何帮助.

I tried it with and without ''' and tried messing with the in and out file and some other stuff nothing seems to work so any help will be welcomed.

谢谢!

推荐答案

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

It's a little complicated. Your JSON file format contains many <list> data (according to Python interpretation). I wrote you a quick and simple solution - see the source code below. However, it would like to improve the code for the custom parser, or to improve the transformation from JSON to Python and vice versa. You could also truncate the OOP code into a single row like: data = json.loads(open('/tmp/a.json','r').read()). But you wrote that you are still new to Python. So on multiple lines it's better for understanding. Test over the Python console, otherwise you must paste all variables into 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))

这篇关于Python-删除JSON文件中的代码行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆