user61629 user61629 - 1 year ago 127
JSON Question

Building Json with string interpolation in python

I have the following :

max_id = 10
for i in range(max_id):
payload = "{\"text\": R%s,\"count\":\"1 \",}" %(i)

I want to iterate through this , and have the value of the json payload be set to "R1", "R2" ... Upon debugging the output is:

>>> payload
Out[1]: '{"text": R0,"count":"1 ",}'

I need it to be

Out[1]: '{"text": "R0","count":"1 ",}'

I've tried a variety of things that haven't worked:

>>> payload = "{\"text\": %s,\"count\":\"1 \"}" % ("'R'+str(i)")
>>> payload
Out[2]: '{"text": \'R\'+str(i),"count":"1 "}'
>>> payload = "{\"text\": \"%s\",\"count\":\"1 \" }" % ('R'+str(i))
>>> payload
Out[4]: '{"text": \'R\'+str(i),"count":"1 "}'
>>> payload = "{\"text\": %s,\"count\":\"1 \" }" % ('"'+'R'+str(i)+'"')
>>> payload
Out[6]: '{"text": \'R\'+str(i),"count":"1 "}'
>>> payload = "{\"text\": %s,\"count\":\"1 \" }" % ('"'+'R'+str(i)+'"')
>>> payload
Out[8]: '{"text": \'R\'+str(i),"count":"1 "}'
>>> payload = "{\"text\": %s,\"count\":\"1 \" }" % ("+'R'+str(i)+")

How can I get this working?

Answer Source

Don't do this with string interpolation. Use an actual JSON dumper:

import json
payload = json.dumps({"text": 'R'+str(i), "count": "1 "})

If you really wanted to do it with string interpolation, you could add the missing quotes to the format string, but it's not a good habit to get into. You'd just run into further problems later on with characters that need to be escaped and minor differences between JSON syntax and Python literal syntax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download