我正在尝试制作一个 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/