在json文件中使用变量 [英] Using variables inside json file

查看:479
本文介绍了在json文件中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to define a variable once and use it throughout the json file.

这是我的MWE :(改编自此处)

Here is my MWE: (adapted from 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",这是我在文件开头定义的.

The access_key field of the objects objectB and objectA must be equal to "abc", which is defined by me in the beginning of the file.

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

How can I achieve this goal in python?

推荐答案

JSON不允许引用变量

在YAML中,您可以定义变量,为其设置参考名称,然后稍后在文件中重复使用它们.

JSON does not allow variable referencing

In YAML, you may define variables, set reference names for them and then reuse them later on in the file.

JSON不提供这种功能,您必须自己逐个设置这些值.

JSON does not provide this sort of functionality, you have to set these values yourself place by place.

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很容易编辑,因此它可能是配置文件的不错选择.

Use YAML anchors and references

You might use YAML feature for this purpose. As YAML is rather easy to edit, it could be good option for config files.

在使用它之前,请确保已安装pyyaml:

Before you use it, be sure, you install pyyaml:

$ pip install pyyaml

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

Then the code (with modified names in variables to fit our needs):

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"
 }
}

这篇关于在json文件中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆