15

I'm trying to encode a somewhat large JSON in Python (v2.7) and I'm having trouble putting in my variables!

As the JSON is multi-line and to keep my code neat I've decided to use the triple double quotation mark to make it look as follows:

my_json = """{
        "settings": {
                "serial": "1",
                "status": "2",
                "ersion": "3"
        },
        "config": {
                "active": "4",
                "version": "5"
        }
}"""

To encode this, and output it works well for me, but I'm not sure how I can change the numbers I have there and replace them by variable strings. I've tried:

    "settings": {
            "serial": 'json_serial',

but to no avail. Any help would be appreciated!

2
  • 2
    Bluntly -- why would you hardcode a JSON string, rather than hardcoding a Python data structure and converting it to JSON when it's time for output? Feb 24, 2017 at 16:56
  • @CharlesDuffy Because I don't know how else to do it. Feb 24, 2017 at 17:02

2 Answers 2

34

Why don't you make it a dictionary and set variables then use the json library to make it into json

import json
json_serial = "123"
my_json = {
    'settings': {
        "serial": json_serial,
        "status": '2',
        "ersion": '3',
    },
    'config': {
        'active': '4',
        'version': '5'
    }
}
print(json.dumps(my_json))
3
  • This works great! But, I'm trying to have it show up all tiny and organized, so I have an extra: "json.dumps(json.loads(my_json), indent=4, sort_keys=True)" which is giving me the error: TypeError: expected string or buffer. Any idea's? Feb 24, 2017 at 17:04
  • 3
    @user5740843, get rid of the json.loads call -- the input object is just a native Python data type, not JSON at all, so it's already ready to be passed as the first argument to json.dumps() exactly as-is. So: json.dumps(my_json, indent=4, sort_keys=True) Feb 24, 2017 at 17:05
  • Briliant. Thank you! Feb 27, 2017 at 10:22
2

If you absolutely insist on generating JSON with string concatenation -- and, to be clear, you absolutely shouldn't -- the only way to be entirely certain that your output is valid JSON is to generate the substrings being substituted with a JSON generator. That is:

'''"settings" : {
  "serial"   : {serial},
  "version"  : {version}
}'''.format(serial=json.dumps("5"), version=json.dumps(1))

But don't. Really, really don't. The answer by @davidejones is the Right Thing for this scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.