【问题标题】:Using variables inside json file在 json 文件中使用变量
【发布时间】:2014-05-26 12:11:28
【问题描述】:

我需要定义一个变量并在整个 json 文件中使用它。

这是我的 MWE:(改编自 here

{
  "variables": {
    "my_access_key": "abc",
    "my_secret_key": "def"
  },
  "objectB": {
    "type": "1",
    "access_key": "{{user `my_access_key`}}",
    "secret_key": "{{user `my_secret_key`}}"
  },
  "objectA": {
    "type": "2",
    "access_key": "{{user `my_access_key`}}",
    "secret_key": "{{user `my_secret_key`}}"
  }
}

对象objectBobjectAaccess_key字段必须等于我在文件开头定义的“abc”。

如何在 python 中实现这个目标?

【问题讨论】:

  • 您不能在 JSON 文件中使用变量。这个 JSON 文件的用途是什么?

标签: python json


【解决方案1】:

JSON 不允许变量引用

在 YAML 中,您可以定义变量,为它们设置引用名称,然后稍后在文件中重用它们。

JSON 不提供此类功能,您必须自己设置这些值。

以编程方式构建的 JSON

import json

access = "AAA"
secret = "XXX"

dct = {"variables": {"my_access_key": access, "my_secret_key": secret},
       "objectB": {"type": "1", "access_key": access, "secret_key": secret},
       "objectA": {"type": "2", "access_key": access, "secret_key": secret}
      }
json_str = json.dumps(dct, indent=True)
print json_str

打印什么

{
 "objectA": {
  "access_key": "AAA", 
  "secret_key": "XXX", 
  "type": "2"
 }, 
 "variables": {
  "my_secret_key": "XXX", 
  "my_access_key": "AAA"
 }, 
 "objectB": {
  "access_key": "AAA", 
  "secret_key": "XXX", 
  "type": "1"
 }
}

使用 YAML 锚点和引用

您可以为此目的使用 YAML 功能。由于 YAML 相当容易编辑,因此它可能是配置文件的不错选择。

在你使用它之前,一定要安装好pyyaml:

$ pip install pyyaml

然后是代码(在variables 中修改名称以满足我们的需要):

import json
import yaml
yaml_str = """
variables: &keys
    access_key: abc
    secret_key: def
objectB:
    <<: *keys
    type: "1"
objectA:
    <<: *keys
    type: "2"
"""

dct = yaml.load(yaml_str)
json_str = json.dumps(dct, indent=True)
print json_str

打印出来的

{
 "objectA": {
  "access_key": "abc", 
  "secret_key": "def", 
  "type": "2"
 }, 
 "variables": {
  "access_key": "abc", 
  "secret_key": "def"
 }, 
 "objectB": {
  "access_key": "abc", 
  "secret_key": "def", 
  "type": "1"
 }
}

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多