String variable not behaving correctly in json.dumps

Question:

I’ve got an API request I am sending and I gather the necessary data and compile it in the proper format into a string called compiled_string. When I try to include it in json.dumps, it is being changed so that my API request is not working properly.

print(compiled_string) #Below is how the string is structured for reference
#{"uuid1": {"uuid2": 1.0,"uuid3": 123.0}, "uuid4": {"moreuuids": 2.3}}

#This payload works in the API request if I paste the exact value of compiled_string
payload = json.dumps({
"field1": "value1"
"name" : "funtimes"
"required_data" : {"uuid1": {"uuid2": 1.0,"uuid3": 123.0}, "uuid4": {"moreuuids": 2.3}}
})


#This doesn't work in the API request using the string variable which should contain the exact same data as above
payload_with_variable = json.dumps({
"field1": "value1"
"name" : "funtimes"
"required_data" : compiled_string})

#When debugging I notice escape slashes are added before each double quote and a pair of double quotes are added to the beginning and end of the string as well
#"{"uuid1": {"uuid2": 1.0,"uuid3": 123.0}, "uuid4": {"moreuuids": 2.3}}"}

Should I be trying to adjust the string to make it look like the original string so it can work properly or is there another way to resolve this? I’ve string some string manipulation but that still didn’t appear to work unless I didn’t do it correctly. I tried .replace on the payload to remove backslashes but that didn’t seem to work.

Asked By: Mohammed Mahfuz

||

Answers:

compiled_string is a JSON string, not a dictionary. But the value of required_data should be a dictionary. So you need to parse the JSON to convert it to a dictionary.

payload_with_variable = json.dumps({
    "field1": "value1"
    "name" : "funtimes"
    "required_data" : json.loads(compiled_string)})
Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.