Home > OS >  Writing Python iteration to JSON file using requests
Writing Python iteration to JSON file using requests

Time:07-15

Previously I did this with urllib and I tried to reuse for API that requires a bearer token, the following is meant to iterate through months and pointID to create an API link, my goal is to export this to a JSON file:

import calendar
import requests
import json

pointId = ['207', '233']  

def get_datas(year):
    for point in pointId:
        for month in range(1, 13):
            r = calendar.monthrange(year, month)
            start = f"{year}-{month:0>2d}-01"
            end = f"{year}-{month:0>2d}-{r[1]}"

            url = f"https://apilink/raw?pointID={pointId}&startDateUTC={start}&endDateUTC={end}&interval=mm&summed=1&productTypeID=2"

            payload={}
            headers = {
            'Authorization': 'Bearer abcdefg1234556'
            }

            response = requests.request("GET", url, headers=headers, data=payload)

            data = json.loads(response)
            yield data

datas = []
for year in (2019, 2020, 2021):
    datas.extend(get_datas(year))

with open('PS_Consumption.json', 'w') as json_file:
    json.dump(datas, json_file, indent=4)

I am getting error 'the JSON object must be str, bytes or bytearray, not Response' when running.

CodePudding user response:

json.loads takes a string, not a Response object.

Change this:

data = json.loads(response)

to:

data = json.loads(response.text)

or even to this:

data = response.json()

CodePudding user response:

please see this StackOverflow question. I believe it answers your question perfectly.

Instead of printing it, assign it to a variable and then you can do json.loads(variableHere)

How do I read a response from Python Requests?

  • Related