csv to json convert python pandas code example
Example 1: python convert json to pandas dataframe
dataframe = pd.DataFrame.from_dict(json_data, orient="index")
import json
import pandas as pd
json_string = '{ "name":"John", "age":30, "car":"None" }'
your_json = json.loads(json_string)
print(your_json)
--> {'name': 'John', 'age': 30, 'car': 'None'}
dataframe = pd.DataFrame.from_dict(your_json, orient="index")
print(dataframe)
0
name John
age 30
car None
Example 2: nested json to csv python
import json
import csv
import requests
response = requests.get('https://statsapi.web.nhl.com/api/v1/teams')
json_data = response.json()
def get_leaves(item, key=None):
if isinstance(item, dict):
leaves = {}
for i in item.keys():
leaves.update(get_leaves(item[i], i))
return leaves
elif isinstance(item, list):
leaves = {}
for i in item:
leaves.update(get_leaves(i, key))
return leaves
else:
return {key : item}
fieldnames = set()
for entry in json_data:
fieldnames.update(get_leaves(entry).keys())
with open('output.csv', 'w', newline='') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames=sorted(fieldnames))
csv_output.writeheader()
csv_output.writerows(get_leaves(entry) for entry in json_data)