문제

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?

도움이 되었습니까?

해결책

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 }}.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top