I'm developing a function that gets a dictionary as string and I need to append to another one as dictionary. After that, I need to parse it like JSON to do a post request. My problem is that I can't parse properly and the final JSON don't have a nested dictionary. The function is like this:
def namefunction(field_string):
dfield01 = "1234567890"
dfield02 = "abcdefgh"
headers = { 'content-type': 'application/json', 'Accept-Charset': 'UTF-8' }
endpoint = "https://url.to.endpoint"
dataSend= { "dfield01": dfield01, "dfield02": dfield02 }
dataSend["field_string"] = json.loads(field_string)
r = request.post(url=endpoint, data=json.dumps(dataSend), headers=headers)
return HttpResponse(r, mimetype='aplication/javascript')
The string that I get in this function is like this:
field_string = '{"0":"whatever 000","1":"whatever 001\nwhatever001b","2":"whatever 002\nwhatever 002b"}'
I'm using Python2.7 (I can't change that).
#### 2019-09-17 Update
Thank for your suggestion @alex. I did a similar aproach using json.loads(), but when I try to put the output in another dictionary, the first one loses his format. I will try to explain with an example:
With this...
# the same -> field = json.loads(field_string)
field = ast.literal_eval(field_string)
return HttpResponse(field, mimetype='application/javascript')
I get a JSON format in the output, but if I do this ...
data = { "name_field": json.loads(field_string) }
... or this:
data = { "name_field": ast.literal_eval(field_string) }
When I check the data output, I get a string in the value. What I'm doing wrong?
####
Any clues, please?
Regards.