Using variables inside json file

json, python

Solution

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

Problem

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?

Original source