JSON to CSV converter in python code example
Example 1: python csv string to json
import json
import csv
//string_data is your string in csv format
json.dumps(list(csv.DictReader(string_data.splitlines(), delimiter=",")))
Example 2: convert csv to json python
import pandas as pd
df = pd.read_csv (r'Path where the CSV file is saved\File Name.csv')
df.to_json (r'Path where the new JSON file will be stored\New File Name.json')
Example 3: 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)