Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - Using variables inside json file

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

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.

How can I achieve this goal in python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...