【发布时间】:2021-12-14 12:18:07
【问题描述】:
我试图找到一个合适的脚本来遍历 .json 文件的文件夹并更新一行。
以下是位于路径中的示例 json 文件。我想遍历一个文件夹中的 json 文件,该文件夹包含多个类似这样的文件以及各种信息,并将“seller_fee_basis_points”从“0”更新为“500”并保存。
非常感谢您的帮助。
{
"name": "Solflare X NFT",
"symbol": "",
"description": "Celebratory Solflare NFT for the Solflare X launch",
"seller_fee_basis_points": 0,
"image": "https://www.arweave.net/abcd5678?ext=png",
"animation_url": "https://www.arweave.net/efgh1234?ext=mp4",
"external_url": "https://solflare.com",
"attributes": [
{
"trait_type": "web",
"value": "yes"
},
{
"trait_type": "mobile",
"value": "yes"
},
{
"trait_type": "extension",
"value": "yes"
}
],
"collection": {
"name": "Solflare X NFT",
"family": "Solflare"
},
"properties": {
"files": [
{
"uri": "https://www.arweave.net/abcd5678?ext=png",
"type": "image/png"
},
{
"uri": "https://watch.videodelivery.net/9876jkl",
"type": "unknown",
"cdn": true
},
{
"uri": "https://www.arweave.net/efgh1234?ext=mp4",
"type": "video/mp4"
}
],
"category": "video",
"creators": [
{
"address": "SOLFLR15asd9d21325bsadythp547912501b",
"share": 100
}
]
}
}
在@JCaesar 的帮助下更新了答案
import json
import glob
import os
SOURCE_DIRECTORY = r'my_favourite_directory'
KEY = 'seller_fee_basis_points'
NEW_VALUE = 500
for file in glob.glob(os.path.join(SOURCE_DIRECTORY, '*.json')):
json_data = json.loads(open(file, encoding="utf8").read())
# note that using the update method means
# that if KEY does not exist then it will be created
# which may not be what you want
json_data.update({KEY: NEW_VALUE})
json.dump(json_data, open(file, 'w'), indent=4)
【问题讨论】:
-
你能把你写的代码贴出来吗?
-
您是否希望将该键更新为所有文件的相同值?
-
你坚持哪一部分?遍历文件夹中的所有文件,或更改 JSON 文件中的值。 (注意:JSON 行中没有“行”。)
-
使用一点 bash、jq 和 sed 将是一种(更快)的方式来做到这一点,但你肯定标记了这个 python。
-
@JCaesar 是的,我想将密钥编辑为所有人的相同值。