Asim
Asim

Reputation: 21

How to dynamically create a JSON string?

I am trying to create a JSON string that I can send in a PUT request but build it dynamically. For example, once I am done, I'd like the string to look like this:

{
    "request-id": 1045058,
    "db-connections":
        [
            {
                "db-name":"Sales",
                "table-name":"customer"
            }
        ]
}

I'd like to use constants for the keys, for example, for request-id, I'd like to use CONST_REQUEST_ID. So the keys will be,

CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"

The values for the keys will be taken from various variables. For example we can take value "Sales" from a var called dbname with the value "Sales".

I have tried json.load and getting exception. Help would be appreciated please as I am a bit new to Python.

Upvotes: 0

Views: 245

Answers (2)

Fan Zeng
Fan Zeng

Reputation: 171

You can concat the string using + with variables.

CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"

request_id = "1045058"
db_name = "Sales"
table_name = 'customer'

json_string = '{' + \
    '"' + CONST_REQUEST_ID + '": ' + request_id \
    + ',' + \
    '"db-connections":' \
    +   '[' \
    +       '{' \
    +            '"' + CONST_DB_NAME +'":"' + db_name +  '",' \
    +           '"' + CONST_TABLE_NAME + '":"' + table_name + '"' \
    +        '}' \
    +    ']' \
    + '}'

print json_string

And this is the result

python st_ans.py 
{"request-id": 1045058,"db-connections":[{"db-name":"Sales","table-name":"customer"}]}

Upvotes: 0

Shadow
Shadow

Reputation: 9427

Create a normal python dictionary, then convert it to JSON.

raw_data = {
    CONST_DB_NAME: getDbNameValue()
}

# ...

json_data = json.dumps(raw_data)
# Use json_data in your PUT request.

Upvotes: 1

Related Questions