阅读JSON文件时替换其中的变量

ldioqlga  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(139)

我有一个JSON文件,其中存储了一系列的“动作”和他们的“指令”。他们是一些常量,将在多个指令。为了方便更新,有另一个JSON块来存储这些常量和他们的值。例如:

{
    "actions": {
        "download_file": "User required to download the file from server_demo",
        "install_application": "Application have to be installed in local_path",
        "upload_file": "User may upload file to server_demo"
    },
    "constants":{
        "server_demo": "http://demo.myserver.com",
        "local_path": "C:\\temp"
    }  
}

当查询一个动作的指令时,我想用“constants”中的变量替换我的代码

import json

def get_instruction(given_action) -> str:
    with open('test.json', 'r') as f:
        j = json.load(f)
    instruction = j['actions'][given_action]
    for const, val in j['constants'].items():
        if const in instruction:
            instruction = instruction.replace(const, val)
    return instruction

print(get_instruction('download_file'))

我不知道这是一个Python的方式来这样做,或者我不应该使用JSON放在首位,如果处理这样的数据?需要一些输入或建议,谢谢!

bnl4lu3b

bnl4lu3b1#

为了以防万一,您还可以使用带有f-string的函数,如下所示:

def get_instruction(values):
    return {
        "download_file": f"User required to download the file from {values['server_demo']}",
        "install_application": f"Application have to be installed in {values['local_path']}",
        "upload_file": f"User may upload file to {values['server_demo']}"
    }

constants = {
    "server_demo": "http://demo.myserver.com",
    "local_path": "C:\\temp"
}

instructions = get_instruction(constants)
print(instructions['download_file'])
# Output : User required to download the file from http://demo.myserver.com

相关问题