Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multi-line JSON and variables

Tags:

python

json

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!

like image 271
user5740843 Avatar asked Feb 24 '17 16:02

user5740843


People also ask

Are multi-line strings allowed in JSON?

And that's it! Now you can store multi-line strings in JSON. It may not be the prettiest or most elegant solution in the world, but given the constraints of JSON, we like to think it works pretty well.

How do I create a multiline in JSON?

JSON does not allow real line-breaks. You need to replace all the line breaks with \n .

Can JSON string contain newline?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.


1 Answers

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))
like image 151
davidejones Avatar answered Sep 30 '22 15:09

davidejones