【问题标题】:Dynamically update json files based on config in pythonpython中根据config动态更新json文件
【发布时间】:2022-07-18 23:29:12
【问题描述】:

假设我有一个这样的配置文件,其中列出了一堆值。我正在运行一个函数,我在其中检查一组字符串是否总是以这些定义的值之一开头。

start_values = [
    "cats",
    "dogs",
    "birds",
    "horses"
]

我还有一个 json 文件,我想在上面运行单元测试以确保我的函数正常运行,就像这样。

{
    "sentence_tests": [
        "horses eat grass.",
        "birds fly high.",
        "cats like to nap.",
        "dogs are cool."
    ]
}

但是,我面临的问题是,如果我想将我的 start_values 之一更改为其他值,我还想更新我的 json 文件以获取该特定值。例如,如果我将“dogs”更改为“cows”,我希望它在我的 json 文件中自动更新,而不必手动更新。

所以这就是我更改 start_values 后想要的样子:

修改 start_values:

start_values = [
    "cats",
    "cows",
    "birds",
    "horses"
]

修改后的json文件:

{
    "sentence_tests": [
        "horses eat grass.",
        "birds fly high.",
        "cats like to nap.",
        "cows are cool."
    ]
}

有没有办法在 python 中做到这一点?

【问题讨论】:

    标签: python


    【解决方案1】:

    是的,

    您可以使用 json python library 轻松加载 JSON 对象。它将转换为 python 字典。之后您所要做的就是重写文件。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2015-04-02
      • 2020-10-08
      相关资源
      最近更新 更多