Julius Kibunjia commited on
Commit
6df230f
·
1 Parent(s): 5890b75

Add DuckDB: Loading JSON notebook

Browse files
Files changed (1) hide show
  1. duckdb/009_loading_json.py +261 -0
duckdb/009_loading_json.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import marimo
2
+
3
+ __generated_with = "0.11.20"
4
+ app = marimo.App(width="medium")
5
+
6
+
7
+ @app.cell
8
+ def _():
9
+ import marimo as mo
10
+ from pathlib import Path
11
+ return Path, mo
12
+
13
+
14
+ @app.cell(hide_code=True)
15
+ def _(mo):
16
+ mo.md(
17
+ r"""
18
+ # Loading JSON
19
+
20
+ DuckDB supports reading and writing JSON through the `json` extension that should be present in most distributions and is autoloaded on first-use. If it's not you can [install and load](https://duckdb.org/docs/stable/data/json/installing_and_loading.html) it manually like any other extension.
21
+
22
+ In this tutorial we'll cover 4 different ways we can transfer JSON data in and out of DuckDB:
23
+
24
+ - [`FROM`](https://duckdb.org/docs/stable/sql/query_syntax/from.html) statement.
25
+ - [`read_json`](https://duckdb.org/docs/stable/data/json/loading_json#the-read_json-function) function.
26
+ - [`COPY`](https://duckdb.org/docs/stable/sql/statements/copy#copy--from) statment.
27
+ - [`IMPORT DATABASE`](https://duckdb.org/docs/stable/sql/statements/export.html) statement.
28
+ """
29
+ )
30
+ return
31
+
32
+
33
+ @app.cell(hide_code=True)
34
+ def _(mo):
35
+ mo.md(
36
+ r"""
37
+ ## Using `FROM`
38
+
39
+ Loading data using `FROM` is simple and straightforward. We use a path or URL to the file we want to load where we'd normally put a table name. When we do this DuckDB attempts to infer the right way to read the file including the correct format and column types. In most cases this is all we need to load data into DuckDB.
40
+ """
41
+ )
42
+ return
43
+
44
+
45
+ @app.cell
46
+ def _(mo):
47
+ _df = mo.sql(
48
+ f"""
49
+ SELECT * FROM 'https://raw.githubusercontent.com/vega/vega-datasets/refs/heads/main/data/cars.json';
50
+ """
51
+ )
52
+ return
53
+
54
+
55
+ @app.cell(hide_code=True)
56
+ def _(mo):
57
+ mo.md(
58
+ r"""
59
+ ## Using `read_json`
60
+
61
+ For greater control over how the JSON is read, we can directly call the [`read_json`](https://duckdb.org/docs/stable/data/json/loading_json#the-read_json-function) function. It supports a few different arguments some common ones are:
62
+
63
+ - `format='array'` or `format='newline_delimited'` - the former tells DuckDB that the rows should be read from a top-level JSON array while latter means the rows should be read from JSON objects separated by a newline (JSONL/NDJSON).
64
+ - `ignore_errors=true` - skips lines with parse errors when reading newline delimited JSON.
65
+ - `columns={columnName: type, ...}` - lets you set types for individual columns manually.
66
+ - `dateformat` and `timestampformat` - controls how DuckDB attempts to parse [Date](https://duckdb.org/docs/stable/sql/data_types/date) and [Timestamp](https://duckdb.org/docs/stable/sql/data_types/timestamp) types. Use the format specifiers specified in the [docs](https://duckdb.org/docs/stable/sql/functions/dateformat.html#format-specifiers).
67
+
68
+ We could rewrite the previous query more explicitly as:
69
+ """
70
+ )
71
+ return
72
+
73
+
74
+ @app.cell
75
+ def _(mo):
76
+ cars_df = mo.sql(
77
+ f"""
78
+ SELECT *
79
+ FROM
80
+ read_json(
81
+ 'https://raw.githubusercontent.com/vega/vega-datasets/refs/heads/main/data/cars.json',
82
+ format = 'array',
83
+ columns = {{
84
+ Name:'VARCHAR',
85
+ Miles_per_Gallon:'FLOAT',
86
+ Cylinders:'FLOAT',
87
+ Displacement:'FLOAT',
88
+ Horsepower:'FLOAT',
89
+ Weight_in_lbs:'FLOAT',
90
+ Acceleration:'FLOAT',
91
+ Year:'DATE',
92
+ Origin:'VARCHAR'
93
+ }},
94
+ dateformat = '%Y-%m-%d'
95
+ )
96
+ ;
97
+ """
98
+ )
99
+ return (cars_df,)
100
+
101
+
102
+ @app.cell
103
+ def _(mo):
104
+ mo.md(r"""Other than singular files we can read [multiple files](https://duckdb.org/docs/stable/data/multiple_files/overview.html) at a time by either passing a list of files or a UNIX glob pattern.""")
105
+ return
106
+
107
+
108
+ @app.cell(hide_code=True)
109
+ def _(mo):
110
+ mo.md(
111
+ r"""
112
+ ## Using `COPY`
113
+
114
+ `COPY` is for useful both for importing and exporting data in a variety of formats including JSON. For example we can import data into an existing table from a JSON file.
115
+ """
116
+ )
117
+ return
118
+
119
+
120
+ @app.cell
121
+ def _(mo):
122
+ _df = mo.sql(
123
+ f"""
124
+ CREATE OR REPLACE TABLE cars2 (
125
+ Name VARCHAR,
126
+ Miles_per_Gallon VARCHAR,
127
+ Cylinders VARCHAR,
128
+ Displacement FLOAT,
129
+ Horsepower FLOAT,
130
+ Weight_in_lbs FLOAT,
131
+ Acceleration FLOAT,
132
+ Year DATE,
133
+ Origin VARCHAR
134
+ );
135
+ """
136
+ )
137
+ return (cars2,)
138
+
139
+
140
+ @app.cell
141
+ def _(cars2, mo):
142
+ _df = mo.sql(
143
+ f"""
144
+ COPY cars2 FROM 'https://raw.githubusercontent.com/vega/vega-datasets/refs/heads/main/data/cars.json' (FORMAT json, ARRAY true, DATEFORMAT '%Y-%m-%d');
145
+ SELECT * FROM cars2;
146
+ """
147
+ )
148
+ return
149
+
150
+
151
+ @app.cell(hide_code=True)
152
+ def _(mo):
153
+ mo.md(r"""Similarly, we can write data from a table or select statement to a JSON file. For example we create a new JSONL file with just the car names and miles per gallon. We first create a temporary directory to avoid cluttering our project directory.""")
154
+ return
155
+
156
+
157
+ @app.cell
158
+ def _(Path):
159
+ from tempfile import TemporaryDirectory
160
+ TMP_DIR = TemporaryDirectory()
161
+ COPY_PATH = Path(TMP_DIR.name) / 'cars_mpg.jsonl'
162
+ print(COPY_PATH)
163
+ return COPY_PATH, TMP_DIR, TemporaryDirectory
164
+
165
+
166
+ @app.cell
167
+ def _(COPY_PATH, cars2, mo):
168
+ _df = mo.sql(
169
+ f"""
170
+ COPY (
171
+ SELECT
172
+ Name AS car_name,
173
+ "Miles_per_Gallon" AS mpg
174
+ FROM cars2
175
+ WHERE mpg IS NOT null
176
+ ) TO '{COPY_PATH}' (FORMAT json);
177
+ """
178
+ )
179
+ return
180
+
181
+
182
+ @app.cell
183
+ def _(COPY_PATH, Path):
184
+ Path(COPY_PATH).exists()
185
+ return
186
+
187
+
188
+ @app.cell(hide_code=True)
189
+ def _(mo):
190
+ mo.md(
191
+ r"""
192
+ ## Using `IMPORT DATABASE`
193
+
194
+ The last method we can use to load JSON data is using the `IMPORT DATABASE` statement. It works in conjunction with `EXPORT DATABASE` to save and load an entire database to and from a directory. For example let's try and export our default in-memory database.
195
+ """
196
+ )
197
+ return
198
+
199
+
200
+ @app.cell
201
+ def _(Path, TMP_DIR):
202
+ EXPORT_PATH = Path(TMP_DIR.name) / 'cars_export'
203
+ print(EXPORT_PATH)
204
+ return (EXPORT_PATH,)
205
+
206
+
207
+ @app.cell
208
+ def _(EXPORT_PATH, mo):
209
+ _df = mo.sql(
210
+ f"""
211
+ EXPORT DATABASE '{EXPORT_PATH}' (FORMAT json);
212
+ """
213
+ )
214
+ return
215
+
216
+
217
+ @app.cell
218
+ def _(EXPORT_PATH, Path):
219
+ list(Path(EXPORT_PATH).iterdir())
220
+ return
221
+
222
+
223
+ @app.cell(hide_code=True)
224
+ def _(mo):
225
+ mo.md(r"""We can then load the database back into DuckDB.""")
226
+ return
227
+
228
+
229
+ @app.cell
230
+ def _(EXPORT_PATH, mo):
231
+ _df = mo.sql(
232
+ f"""
233
+ DROP TABLE IF EXISTS cars2;
234
+ IMPORT DATABASE '{EXPORT_PATH}';
235
+ SELECT * FROM cars2;
236
+ """
237
+ )
238
+ return
239
+
240
+
241
+ @app.cell(hide_code=True)
242
+ def _(TMP_DIR):
243
+ TMP_DIR.cleanup()
244
+ return
245
+
246
+
247
+ @app.cell(hide_code=True)
248
+ def _(mo):
249
+ mo.md(
250
+ r"""
251
+ ## Further Reading
252
+
253
+ - Complete information on the JSON support in DuckDB can be found in their [documentation](https://duckdb.org/docs/stable/data/json/overview.html).
254
+ - You can also learn more about using SQL in marimo from the [examples](https://github.com/marimo-team/marimo/tree/main/examples/sql).
255
+ """
256
+ )
257
+ return
258
+
259
+
260
+ if __name__ == "__main__":
261
+ app.run()