Using variables inside json file

后端 未结 1 1563
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 13:25

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

Here is my MWE: (adapted from here)

{
  \"variables\": {
    \"my_access_key\":         


        
相关标签:
1条回答
  • 2021-01-03 13:49

    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 does not provide this sort of functionality, you have to set these values yourself place by place.

    JSON built programmatically

    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
    

    what prints

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

    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.

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

    $ pip install pyyaml
    

    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
    

    which prints

    {
     "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"
     }
    }
    
    0 讨论(0)
提交回复
热议问题