【问题标题】:Iterate and update through folder of .json files and update value in python通过.json文件的文件夹迭代和更新并更新python中的值
【发布时间】: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 是的,我想将密钥编辑为所有人的相同值。

标签: python json loops


【解决方案1】:

我建议使用 glob 来查找您感兴趣的文件。然后利用 json 模块来读取和写入 JSON 内容。

这非常简洁,没有健全性检查/异常处理,但你应该明白:

import json
import glob
import os

SOURCE_DIRECTORY = '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).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)

【讨论】:

  • 非常感谢!必须进行一些帮助我到达终点线的轻微编辑将更新主要帖子。有一个编码错误,所以不得不添加到 open() 函数
猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多