簡體   English   中英

如何使用 Python 腳本更改多個 JSON 文件中的屬性 trait_type 值(從 int 到 str)?

[英]How can I change an attribute trait_type value (from a int to a str) in multiple JSON files using a Python script?

"attributes": [
    {
      "trait_type": "Vintage",
      "value": 2019
    },
    {
      "trait_type": "Volume (ml)",
      "value": 750
    }
]

我想使用 python 將 2019 和 750 更改為超過 150 個 JSON 的多個值的字符串(通過包含“”)

我不是開發人員,也不使用 Python,但到目前為止我有這個:

import json

for i in range(1, 147):
    with open(f'{i}.json', 'r+', encoding='utf8') as f:
        data = json.load(f)

您可以制作一個 function,它采用 JSON 文件名並替換您要查找的這些特定值:

def change_values_to_string(json_filename):
    with open(f'{json_filename}.json', 'r') as json_fp:
        json_to_dict = json.loads(json_fp.read())

    for sub_dict in json_to_dict["attributes"]:
        sub_dict["value"] = str(sub_dict["value"])

    with open(f'{json_filename}.json', 'w') as json_fp:
        json_fp.write(json.dumps(json_to_dict))


for _ in range(1, 147):
    change_values_to_string(_)

輸入:

test.json

{
  "attributes": [
    {
      "trait_type": "Vintage",
      "value": 2019
    },
    {
      "trait_type": "Volume (ml)",
      "value": 750
    }
]
}

使用正確的文件名調用 function: change_values_to_string("test")輸出:


{
  "attributes": [
    {
      "trait_type": "Vintage",
      "value": "2019"
    },
    {
      "trait_type": "Volume (ml)",
      "value": "750"
    }
  ]
}

說明:

  1. 以讀取模式打開 json 文件 - 並將其加載到字典 python 類型中。
  2. 如果我做對了,遍歷包含很多字典的attributes鍵。
  3. 將每個value鍵替換為字符串
  4. 將字典轉儲到覆蓋它的同一個文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM