csv to json convert python pandas code example

Example 1: python convert json to pandas dataframe

# Basic syntax:
dataframe = pd.DataFrame.from_dict(json_data, orient="index")

# Example usage:
import json
import pandas as pd

# Make json-formatted string:
json_string = '{ "name":"John", "age":30, "car":"None" }'
your_json = json.loads(json_string)
print(your_json)
--> {'name': 'John', 'age': 30, 'car': 'None'}

# Convert to pandas dataframe:
dataframe = pd.DataFrame.from_dict(your_json, orient="index")
print(dataframe)
         0
name  John
age     30
car   None

# Note, orient="index" sets the keys as rownames. orient="columns" is
#	the default and is supposed to set the keys as column names, but I
#	couldn't seem to get it to work with this example

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}

# First parse all entries to get the complete fieldname list
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)