python 替换嵌套json文件中的一个变量

qv7cva1a  于 2023-03-21  发布在  Python
关注(0)|答案(2)|浏览(153)

我有以下JSON文件名为info.json:

{
    "jobs": [
        
        {
            "type": "Account",
            "min": 5,
            "max": 15,
            "arguments": {
                "inix": 48,
                "load": "3.081579e+07",
                "overload": "6.508037e+07"

            },
            "attributes": {
                "name": "emp_1",
                "priority_type": "low",
                "dependency": "-"
            }
        },
        {
            "type": "detect",
            "min": 5,
            "max": 13,
            "arguments": {
                "inix": 748,
                "load": "3.081579e+07",
                "overload": "6.508037e+07"

            },
            "attributes": {
                "name": "emp_2",
                "priority_type": "high",
                "dependency": "-"
            }
        },
         {
            "type": "Account",
            "min": 5,
            "max": 15,
            "arguments": {
                "inix": 48,
                "load": "3.081579e+07",
                "overload": "6.508037e+07"

            },
            "attributes": {
                "name": "emp_3",
                "priority_type": "low",
                "dependency": "-"
            }
        }
      
        
    ]
}

我试着写了下面的python代码,从csv文件中取一个dependency的值,然后把它写出来,而不是“-”。我需要的是把每次出现的“-”替换为从csv文件中读取的job_dependency值。

path='/load/statistics.csv'

for repeat in range(repeats):
        job_statistics = pd.read_csv(path)
        job_dependency = job_statistics['dependency'][repeat]
        print(job_exe_time)
        temp["attributes"]["dependency"]= f"{job_dependency}"

        with open("data_inv_jobs50.json", "wt") as fout:
                for line in file_data:
                         fout.write(line.replace("-","{job_exe_time}"))

我需要替换“dependency”的值:带“dependency”的“-”:“value from csv”,但是我上面的代码不好用..有什么建议吗?

svmlkihl

svmlkihl1#

我想到了这个:

import json

if __name__ == "__main__":
    # Retrieving the dependency value
    value_from_csv = 150
    # Opening the json file
    with open("info.json", "r", encoding="utf-8") as file:
        json_dict = json.load(file)
    # Modifying the json object
    for i in range(len(json_dict["jobs"])):
        json_dict["jobs"][i]["attributes"]["dependency"] = value_from_csv
    # Re-writing the object in a json file
    with open("info2.json", "w", encoding="utf-8") as file:
        json.dump(json_dict, file, indent=4)

在这里我假设只有一个依赖项值。在这种情况下,你可以(也应该)首先检索这个值,然后再进入你将用来修改文件内容的循环。

w1e3prcc

w1e3prcc2#

您可以使用以下脚本将'-'值替换为所需的值。

for item in dic['jobs']:
...:     item['attributes']['dependency'] = value_from_csv

相关问题