0

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.

1
  • You mean something like "db-name" : dbname? Commented Jul 18, 2019 at 23:59

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.