Pregunta

Hi I need to make API calls to collect some data. The URL looks like this:

https://app.example.com/SearchService/search/xref?parts=[{"partNumber":"myproduct","manufacturer":"my company"}]&fmt=json

I try to replace the partnumber value with a list of different products and I am thinking about using substring replacement.

>>> print "My name is {0}".format('/usr/bin')
My name is /usr/bin

However, while I was trying to do that against the URL:

>>> print 'https://app.example.com/SearchService/search/xref?parts=[{"partNumber":"{0}","manufacturer":"my company"}]&fmt=json'.format('my product')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: '"partNumber"'

Somehow it is trying to evaluate the dictionary inside the string, which is totally beyond my knowledge why it is doing so.

Can anyone help me how to fix it?

¿Fue útil?

Solución

You need to escape the other { and } using {{ and }}:

>>> print 'https://app.example.com/SearchService/search/xref?parts=[{{"partNumber":"{0}","manufacturer":"my company"}}]&fmt=json'.format('my product')
https://app.example.com/SearchService/search/xref?parts=[{"partNumber":"my product","manufacturer":"my company"}]&fmt=json

From docs:

If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top