Last active
July 9, 2020 00:39
-
-
Save ashwch/56d9e5e1e05a9347f85379f81bac82b6 to your computer and use it in GitHub Desktop.
Airtable to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Download Airtable's API response retrieved from browser console as CSV | |
| import csv | |
| import sys | |
| import json | |
| file_path = sys.argv[1] | |
| with open(file_path) as f_in, open("airtable.csv", "w") as f_out: | |
| data = json.load(f_in) | |
| columns_metadata = { | |
| item["id"]: { | |
| "name": item["name"], | |
| "type": item["type"], | |
| "choices": { | |
| choice_id: value["name"] for choice_id, value in ((item.get("typeOptions") or {}).get("choices") or {}).items() | |
| } | |
| } | |
| for item in data["data"]["table"]["columns"] | |
| } | |
| headers = [item["name"] for item in columns_metadata.values()] | |
| rows = data["data"]["table"]["rows"] | |
| writer = csv.DictWriter(f_out, fieldnames=headers) | |
| writer.writeheader() | |
| for row in rows: | |
| row_raw_data = row["cellValuesByColumnId"] | |
| row_data = {} | |
| for idx, value in row_raw_data.items(): | |
| col_type = columns_metadata[idx]["type"] | |
| col_name = columns_metadata[idx]["name"] | |
| if col_type == "richText": | |
| value = "\n".join( | |
| [item["insert"] for item in value["documentValue"] if "attributes" not in item] | |
| ) | |
| elif col_type == "multiSelect": | |
| choices = columns_metadata[idx]["choices"] | |
| value = ", ".join( | |
| [choices[item] for item in value] | |
| ) | |
| elif col_type == "select": | |
| choices = columns_metadata[idx]["choices"] | |
| value = choices[value] | |
| row_data[col_name] = value | |
| writer.writerow(row_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment