python - 如何循环 json 文件并根据特定条件更改特定值

标签 python text-processing

我正在尝试制作一个 python 脚本,在其中我可以根据文件内的特定位置更改特定值,在此示例中,具体是一个 json 文件。

json 文件长约 100k,有多个区域指定为 "name": "Box #14", "name": "Box #16", "name": "Box #17" 并且这个列表还在继续。对于每个名称,它都会在名称下方出现一个图像字段,例如"image": ".png",我想编辑该 .png 值,使其基于特定值(取决于名称编号)。例如,如果 "name": "Box #14"image": "13.png" 如果 "name": "Box #15 then "image": "14.png" 等等...

到目前为止我得到的是:

import re
import sys

i = 0
++i

PAT = re.compile('"image": ".png"')

KEYWORDS_PATH = 'images.json'
KEYWORDS = open(KEYWORDS_PATH).read().splitlines()

names = ['"name": ".*"']


def check_all(check, ws):
    return all(re.search(r'\b{}\b'.format(w), check) for w in ws)


with open('images.json') as inp, open('output.json', 'w') as out:

    for name in names:
        if names in KEYWORDS:
            print('Removed the keyword - %s' % names)
            sys.exit()
    for line in inp:
        out.write(PAT.sub('"image": "%s.png"' % i, line))

这使得一切都是 0.png

更新:

这是 json 文件中的一个示例

[
 {
   "name": "Box #14",
   "image": ".png",
   "attributes": [
     {
       "trait_type": "Size",
       "value": "0.8 inch"
     }   
   ]
     "files": [
       {
         "url": ".png",
         "type": "image/png"
       }
     ]
   }
 },

{
   "name": "Box #15",
   "image": ".png",
   "attributes": [
     {
       "trait_type": "Size",
       "value": "2.8 inch"
     }   
   ]
     "files": [
       {
         "url": ".png",
         "type": "image/png"
       }
     ]
   }
 }
]

我想要做的就是将图像字段内的 .png 替换为名称上的数字,但低于例如如上所示Box #14名称我希望将图像从.png替换为13.png

最佳答案

您可以使用内置的json模块来处理json。这是一个完整的示例。

import json
# read the json file
json_txt = """[ { "name": "Box #14", "image": ".png", "attributes": [ { } ], "files": [ { } ] }, { "name": "Box #15", "image": ".png", "attributes": [ { } ], "files": [ { } ] } ]"""

data = json.loads(json_txt)
for val in data:
    number = int(val['name'].split('#')[1])
    val['image'] = f"{number-1}.png"

with open('json_output.json', 'w') as outfile:
    json.dump(data, outfile)

这假设每个部分都有一个名称和一个图像属性。

对于实际数据,您将像这样读取文件:

with open('data.json') as f:
    data = json.load(f)

关于python - 如何循环 json 文件并根据特定条件更改特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70792602/

相关文章:

python - 计算矩阵的零空间

Python Pandas - 比较列文本并提供匹配的字数

python - 如何解析某些文本数据?

python - 删除包含 2 个单词的引号并删除它们之间的逗号

java - 修剪 Java 字符串中不需要的字符

regex - 从行中提取可选字段值

python - 将数组合并为一个字符串

python - 使用 Pandas 保存列中条目的总数

python - 使用 FuncAnimation 在 matplotlib 中动画化等高线图

java - 在java中拆分可视文本 block