1

I am using Requests library in Python to work with a company's API.

However the results are in XML format.

How do I reference the data that I want in Python or using requests? Is there away to convert this data to JSON?

Here is an example:

XML:

    <result xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Starbucks.Location.WebAPI.Models">
<paging>
   <total>21933</total>
   <offset>0</offset>
   <limit>10</limit>
   <returned>10</returned>
</paging>
<stores>
   <store>
      <id>1</id>
      <name>Store1</name>
      <brandName>BrandName</brandName>
      <storeNumber>34601-20281</storeNumber>
   </store>
   <store>
      <id>2</id>
      <name>Store2</name>
      <brandName>BrandName</brandName>
      <storeNumber>20281</storeNumber>
   </store>

My Python code looks a little something like this:

for i in range(0, 1):
   myParameters = {'limit': '50', 'offset': i*50}
   response = requests.get(url, params=myParameters)

   print response #Here is where I want to print the data in json format

In that example response returns xml format.

I would like to create a csv or text file or something using specific attributes of each store. For instance grab the store id and place it in a column in a csv file.

But I don't know how to reference the id tag in the xml result. I figured converting the data to json would help but when I use Requests .json() or json library I get the error: No JSON object could be decoded

0

1 Answer 1

1

There are many XML parsers, however- as you are interested in getting JSON you might want to try xmltodict with json, which can get you there in one line.

json.dumps(xmltodict.parse(response))
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks! So it returns a json object but when I try to get info I get an error: TypeError: string indices must be integers, not str The code I use is newResponse['result']['stores'][1]['name']
Seems you have a Json array instead of dict in of the result, store or name- try to traverse one layer at a time until you figure out the mix up
Then try newResponse[1]
Same error, however I removed json.dumps() and now I get results up until newResponse['result']['stores']...newResponse['result']['stores'][1] returns a different error: KeyError: 1
UPDATE: So, I took out json.dumps() and wrote `newResponse['result']['stores']['store'][1]['name']' and that seemed to work!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.