Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python json.dumps with string interpolation?

Tags:

python

json

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?

like image 762
Manuel G Avatar asked Mar 21 '23 09:03

Manuel G


1 Answers

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.

like image 164
BrenBarn Avatar answered Mar 29 '23 00:03

BrenBarn