jas jas - 1 month ago 9
Python Question

How to extract the data from an ImmutableMultiDict

I receive my data as an ImmutableMultiDict

ImmutableMultiDict([('slim[]', '{"server":[{"status":"SUCCESS"}],"meta":{},"input":{"name":"sample-img.jpg","type":"image/jpeg","size":41319,"width":400,"height":300},"output":{"width":400,"height":300,"image":"data:image/jpeg;base64,/9j/4AAQ....


I convert that to a dict

data = dict(request.form)


After converting to a dict, I end up with the data in this format.

{
'imageUploaded':
['{
"server":[{"status":"SUCCESS"}],
"meta":{},
"input":{
"name":"sample-img.jpg",
"type":"image/jpeg",
"size":41319,
"width":400,
"height":300
},
"output":{"width":400,"height":300,"image":"data:image/jpeg;base64,/9j//WmZyP/2Q=="
},
"actions":
{
"rotation":0,
"crop":{"x":0,"y":0,"width":400,"height":300,"type":"manual"},
"size":
{
"width":640,"height":640
}
}
}']
}


I have tried

data = json.dumps(dict(request.form))
a = json.loads(data)
print(a['imageUploaded']['output']['image'])


But I get this error


TypeError: list indices must be integers, not str

Answer

So this is the data? (I assume you are pretty-printing it because you can't have multi-lined 'string' values)

{
'imageUploaded': 
    ['{    

Then you need data['imageUploaded'][0] to get the first element of that array.

That appears to be a JSON string, so parse that

import json
inner_data = data['imageUploaded'][0]
inner_data = json.loads(inner_data)

And then, you can inner_data['output']['image']

Sample Run