0
$\begingroup$

I have a request that is giving me a JSON answer:

[
    {'metadata': {'plantName': 'Hoover Dam', 'object_name': 'engin_one', 'timeseries_type': 'past', 'model': 'realized', 'date_from': '2020-05-16T00: 00: 00', 'date_to': '2020-05-19T08: 00: 00
        },
         'positions': [
            {'date_time': '2020-05-16T00: 00: 00', 'value': 85.05206819999998
            },
            {'date_time': '2020-05-16T01: 00: 00', 'value': 118.0079838
            },
            {'date_time': '2020-05-16T02: 00: 00', 'value': 126.14453999999998
            },
            {'date_time': '2020-05-16T03: 00: 00', 'value': 190.2320307
            },
            {'date_time': '2020-05-16T04: 00: 00', 'value': 207.15472439999996
            },
            {'date_time': '2020-05-16T05: 00: 00', 'value': 244.4881527
            }
        ]
    }
]

I would like to parse this JSON document into a CSV format.

My current code looks like this:

csvname='O:\STO\filename.csv'
token = "eyJhbGciO"    
url = 'https://api.myaddress.io'
headers={'Authorization': 'Bearer ' + token}
params={'plantName':'Hoover Dam','object_name':'engin_one','timeseries_type':'past','model':'realized'} 
r=requests.get(url,params=params,headers=headers)
result = json.loads(r.text)
df=pd.DataFrame(result)
df.to_csv(csvname)

I currently end up with a two-line CSV document, however, I would like to have a one-line document where the columns are the keys of my JSON document. Something like this:

,metadata,positions
{'plantName': 'Hoover Dam', 'object_name': 'engin_one', 'timeseries_type': 'past', 'model': 'realized', 'date_from': '2020-05-16T00:00:00', 'date_to': '2020-05-19T08:00:00}, 'positions': [{'date_time': '2020-05-16T00:00:00', 'value': 85.05206819999998},....

How can I achieve that?

$\endgroup$
1
  • $\begingroup$ Sorry the two last line result df=pd.DataFrame(result ) And result df.to_csv(csvname) Was meant to be df=pd.DataFrame(result ) df.to_csv(csvname) $\endgroup$ – swissmade May 19 '20 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.