You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We managed to scrape data about products and print it, with each product separated by a new line and each field separated by the `|` character. This already produces structured text that can be parsed, i.e., read programmatically.
Sony XBR-950G BRAVIA 4K HDR Ultra HD TV | 139800 | null
19
19
...
20
20
```
21
21
@@ -27,220 +27,208 @@ We should use widely popular formats that have well-defined solutions for all th
27
27
28
28
Producing results line by line is an efficient approach to handling large datasets, but to simplify this lesson, we'll store all our data in one variable. This'll take three changes to our program:
Before looping over the products, we prepare an empty list. Then, instead of printing each line, we append the data of each product to the list in the form of a Python dictionary. At the end of the program, we print the entire list at once.
75
+
Before looping over the products, we prepare an empty array. Then, instead of printing each line, we append the data of each product to the array in the form of a JavaScript object. At the end of the program, we print the entire array at once.
title: 'JBL Flip 4 Waterproof Portable Bluetooth Speaker',
82
+
minPrice: 7495,
83
+
price: 7495
84
+
},
85
+
{
86
+
title: 'Sony XBR-950G BRAVIA 4K HDR Ultra HD TV',
87
+
minPrice: 139800,
88
+
price: null
89
+
},
90
+
...
91
+
]
74
92
```
75
93
76
-
:::tip Pretty print
94
+
:::tip Spread syntax
95
+
96
+
The three dots in `{ title: titleText, ...priceRange }` are called [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). It's the same as if we wrote the following:
77
97
78
-
If you find the complex data structures printed by `print()` difficult to read, try using [`pp()`](https://docs.python.org/3/library/pprint.html#pprint.pp) from the `pprint` module instead.
98
+
```js
99
+
{
100
+
title: titleText,
101
+
minPrice:priceRange.minPrice,
102
+
price:priceRange.price,
103
+
}
104
+
```
79
105
80
106
:::
81
107
82
-
## Saving data as CSV
108
+
## Saving data as JSON
83
109
84
-
The CSV format is popular among data analysts because a wide range of tools can import it, including spreadsheets apps like LibreOffice Calc, Microsoft Excel, Apple Numbers, and Google Sheets.
110
+
The JSON format is popular primarily among developers. We use it for storing data, configuration files, or as a way to transfer data between programs (e.g., APIs). Its origin stems from the syntax of JavaScript objects, but people now use it accross programming languages.
85
111
86
-
In Python, it's convenient to read and write CSV files, thanks to the [`csv`](https://docs.python.org/3/library/csv.html) standard library module. First let's try something small in the Python's interactive REPL to familiarize ourselves with the basic usage:
112
+
We'll begin with importing the `writeFile` function from the Node.js standard library, so that we can, well, write files:
We first opened a new file for writing and created a `DictWriter()` instance with the expected field names. We instructed it to write the header row first and then added two more rows containing actual data. The code produced a `data.csv` file in the same directory where we're running the REPL. It has the following contents:
120
+
Next, instead of printing the data, we'll finish the program by exporting it to JSON. Let's replace the line `console.log(data)` with the following:
99
121
100
-
```csv title=data.csv
101
-
name,age,hobbies
102
-
Alice,24,"kickbox, Python"
103
-
Bob,42,"reading, TypeScript"
122
+
```js
123
+
constjsonData=JSON.stringify(data);
124
+
awaitwriteFile('products.json', jsonData);
104
125
```
105
126
106
-
In the CSV format, if values contain commas, we should enclose them in quotes. You can see that the writer automatically handled this.
107
-
108
-
When browsing the directory on macOS, we can see a nice preview of the file's contents, which proves that the file is correct and that other programs can read it as well. If you're using a different operating system, try opening the file with any spreadsheet program you have.
109
-
110
-

111
-
112
-
Now that's nice, but we didn't want Alice, Bob, kickbox, or TypeScript. What we actually want is a CSV containing `Sony XBR-950G BRAVIA 4K HDR Ultra HD TV`, right? Let's do this! First, let's add `csv` to our imports:
127
+
That's it! If we run our scraper now, it won't display any output, but it will create a `products.json` file in the current working directory, which contains all the data about the listed products:
113
128
114
-
```py
115
-
import httpx
116
-
from bs4 import BeautifulSoup
117
-
from decimal import Decimal
118
-
# highlight-next-line
119
-
import csv
129
+
<!-- eslint-skip -->
130
+
```json title=products.json
131
+
[{"title":"JBL Flip 4 Waterproof Portable Bluetooth Speaker","minPrice":7495,"price":7495},{"title":"Sony XBR-950G BRAVIA 4K HDR Ultra HD TV","minPrice":139800,"price":null},...]
120
132
```
121
133
122
-
Next, instead of printing the data, we'll finish the program by exporting it to CSV. Replace `print(data)` with the following:
134
+
If you skim through the data, you'll notice that the `JSON.stringify()` function handled some potential issues, such as escaping double quotes found in one of the titles by adding a backslash:
{"title":"Sony SACS9 10\" Active Subwoofer","minPrice":15800,"price":15800}
130
138
```
131
139
132
-
If we run our scraper now, it won't display any output, but it will create a `products.csv` file in the current working directory, which contains all the data about the listed products.
133
-
134
-

135
-
136
-
## Saving data as JSON
137
-
138
-
The JSON format is popular primarily among developers. We use it for storing data, configuration files, or as a way to transfer data between programs (e.g., APIs). Its origin stems from the syntax of objects in the JavaScript programming language, which is similar to the syntax of Python dictionaries.
140
+
:::tip Pretty JSON
139
141
140
-
In Python, there's a [`json`](https://docs.python.org/3/library/json.html) standard library module, which is so straightforward that we can start using it in our code right away. We'll need to begin with imports:
142
+
While a compact JSON file without any whitespace is efficient for computers, it can be difficult for humans to read. You can call `JSON.stringify(data, null, 2)` for prettier output. See [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) for explanation of the parameters and more examples.
141
143
142
-
```py
143
-
import httpx
144
-
from bs4 import BeautifulSoup
145
-
from decimal import Decimal
146
-
import csv
147
-
# highlight-next-line
148
-
import json
149
-
```
144
+
:::
150
145
151
-
Next, let’s append one more export to end of the source code of our scraper:
146
+
## Saving data as CSV
152
147
153
-
```py
154
-
withopen("products.json", "w") asfile:
155
-
json.dump(data, file)
156
-
```
148
+
The CSV format is popular among data analysts because a wide range of tools can import it, including spreadsheets apps like LibreOffice Calc, Microsoft Excel, Apple Numbers, and Google Sheets.
157
149
158
-
That’s it! If we run the program now, it should also create a `products.json` file in the current working directory:
150
+
Neither JavaScript itself nor Node.js offers anything built-in to read and write CSV, so we'll need to install a library. We'll use [json2csv](https://juanjodiaz.github.io/json2csv/), a _de facto_ standard for working with CSV in JavaScript:
159
151
160
152
```text
161
-
$ python main.py
162
-
Traceback (most recent call last):
163
-
...
164
-
raise TypeError(f'Object of type {o.__class__.__name__} '
165
-
TypeError: Object of type Decimal is not JSON serializable
166
-
```
167
-
168
-
Ouch! JSON supports integers and floating-point numbers, but there's no guidance on how to handle `Decimal`. To maintain precision, it's common to store monetary values as strings in JSON files. But this is a convention, not a standard, so we need to handle it manually. We'll pass a custom function to `json.dump()` to serialize objects that it can't handle directly:
153
+
$ npm install @json2csv/node --save
169
154
170
-
```py
171
-
defserialize(obj):
172
-
ifisinstance(obj, Decimal):
173
-
returnstr(obj)
174
-
raiseTypeError("Object not JSON serializable")
175
-
176
-
withopen("products.json", "w") asfile:
177
-
json.dump(data, file, default=serialize)
155
+
added 4 packages, and audited 28 packages in 1s
156
+
...
178
157
```
179
158
180
-
Now the program should work as expected, producing a JSON file with the following content:
159
+
Once installed, we can add the following line to our imports:
If you skim through the data, you'll notice that the `json.dump()` function handled some potential issues, such as escaping double quotes found in one of the titles by adding a backslash:
168
+
Then, let's add one more data export near the end of the source code of our scraper:
188
169
189
-
```json
190
-
{"title": "Sony SACS9 10\" Active Subwoofer", "min_price": "158.00", "price": "158.00"}
170
+
```js
171
+
constparser=newAsyncParser();
172
+
constcsvData=awaitparser.parse(data).promise();
173
+
awaitwriteFile("products.csv", csvData);
191
174
```
192
175
193
-
:::tip Pretty JSON
176
+
The program should now also produce a `data.csv` file. When browsing the directory on macOS, we can see a nice preview of the file's contents, which proves that the file is correct and that other programs can read it. If you're using a different operating system, try opening the file with any spreadsheet program you have.
194
177
195
-
While a compact JSON file without any whitespace is efficient for computers, it can be difficult for humans to read. You can pass `indent=2` to `json.dump()` for prettier output.
178
+

196
179
197
-
Also, if your data contains non-English characters, set `ensure_ascii=False`. By default, Python encodes everything except [ASCII](https://en.wikipedia.org/wiki/ASCII), which means it would save [Bún bò Nam Bô](https://vi.wikipedia.org/wiki/B%C3%BAn_b%C3%B2_Nam_B%E1%BB%99) as `B\\u00fan b\\u00f2 Nam B\\u00f4`.
180
+
In the CSV format, if a value contains commas, we should enclose it in quotes. If it contains quotes, we should double them. When we open the file in a text editor of our choice, we can see that the library automatically handled this:
198
181
199
-
:::
182
+
```csv title=data.csv
183
+
"title","minPrice","price"
184
+
"JBL Flip 4 Waterproof Portable Bluetooth Speaker",7495,7495
185
+
"Sony XBR-950G BRAVIA 4K HDR Ultra HD TV",139800,
186
+
"Sony SACS9 10"" Active Subwoofer",15800,15800
187
+
...
188
+
"Samsung Surround Sound Bar Home Speaker, Set of 7 (HW-NW700/ZA)",64799,64799
189
+
...
190
+
```
200
191
201
-
We've built a Python application that downloads a product listing, parses the data, and saves it in a structured format for further use. But the data still has gaps: for some products, we only have the min price, not the actual prices. In the next lesson, we'll attempt to scrape more details from all the product pages.
192
+
We've built a Node.js application that downloads a product listing, parses the data, and saves it in a structured format for further use. But the data still has gaps: for some products, we only have the min price, not the actual prices. In the next lesson, we'll attempt to scrape more details from all the product pages.
202
193
203
194
---
204
195
205
196
## Exercises
206
197
207
-
In this lesson, you learned how to create export files in two formats. The following challenges are designed to help you empathize with the people who'd be working with them.
198
+
In this lesson, we created export files in two formats. The following challenges are designed to help you empathize with the people who'd be working with them.
208
199
209
-
### Process your CSV
200
+
### Process your JSON
210
201
211
-
Open the `products.csv` file in a spreadsheet app. Use the app to find all products with a min price greater than $500.
202
+
Write a new Node.js program that reads `products.json`, finds all products with a min price greater than $500, and prints each of them.
212
203
213
204
<details>
214
205
<summary>Solution</summary>
215
206
216
-
Let's use [Google Sheets](https://www.google.com/sheets/about/), which is free to use. After logging in with a Google account:
217
-
218
-
1. Go to **File > Import**, choose **Upload**, and select the file. Import the data using the default settings. You should see a table with all the data.
219
-
2. Select the header row. Go to **Data > Create filter**.
220
-
3. Use the filter icon that appears next to `min_price`. Choose **Filter by condition**, select **Greater than**, and enter **500** in the text field. Confirm the dialog. You should see only the filtered data.
207
+
```js
208
+
import { readFile } from"fs/promises";
221
209
222
-

210
+
constjsonData=awaitreadFile("products.json");
211
+
constdata=JSON.parse(jsonData);
212
+
data
213
+
.filter(row=>row.minPrice>50000)
214
+
.forEach(row=>console.log(row));
215
+
```
223
216
224
217
</details>
225
218
226
-
### Process your JSON
219
+
### Process your CSV
227
220
228
-
Write a new Python program that reads `products.json`, finds all products with a min price greater than $500, and prints each one using [`pp()`](https://docs.python.org/3/library/pprint.html#pprint.pp).
221
+
Open the `products.csv` file we created in the lesson using a spreadsheet application. Then, in the app, find all products with a min price greater than $500.
229
222
230
223
<details>
231
224
<summary>Solution</summary>
232
225
233
-
```py
234
-
import json
235
-
from pprint import pp
236
-
from decimal import Decimal
226
+
Let's use [Google Sheets](https://www.google.com/sheets/about/), which is free to use. After logging in with a Google account:
237
227
238
-
withopen("products.json", "r") asfile:
239
-
products = json.load(file)
228
+
1. Go to **File > Import**, choose **Upload**, and select the file. Import the data using the default settings. You should see a table with all the data.
229
+
2. Select the header row. Go to **Data > Create filter**.
230
+
3. Use the filter icon that appears next to `minPrice`. Choose **Filter by condition**, select **Greater than**, and enter **500** in the text field. Confirm the dialog. You should see only the filtered data.
0 commit comments