Python json.dumps with string interpolation?
json, python
Solution
Why not just:
>>> food = "pizza"
>>> json.dumps({"favorite_food":[food]})
'{"favorite_food": ["pizza"]}'
`json,dumps` takes actual values as input --- that is, real dicts, lists, ints, and strings. If you want to put your string value in the dict, just put it in. You don't want to put in a string representation of it, you want to put in the actual value and let `json.dumps` make the string representation.
Problem
Let's say I want to create a json object following the structure: ``` {"favorite_food":["icecream","hamburguers"]} ``` to do so in python, if i know the whole string in advance, I can just do: ``` json.dumps({"favorite_food":["icecream","hamburguers"]}) ``` which works fine. my question though is, how would i do the same thing if i wanted to get the object as a result of a string interpolation? For example: ``` favorite food = 'pizza' json.dumps({"favorite_food":[%s]}) %favorite_food ``` the issue i found is, if I do the interpolation prior to calling the `json.dumps`: ``` dict= '{"favorite_food":[%s]}' % favorite_food ``` if i then do `json.dumps(dict)` , because of the string quotation, the json_dumps returns: ``` {"favorite_food":[pizza]} ``` that is, is not a dict anymore (but a string with the structure of a dict) How can i solve this simple issue?