Skip to content

Commit b7c46d0

Browse files
committed
format type
1 parent 4794ef6 commit b7c46d0

File tree

3 files changed

+43
-25
lines changed

3 files changed

+43
-25
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,13 @@
11
# JSON FROM TABLE
2+
3+
Converts html tables into JSON
4+
5+
## Usage
6+
7+
Install via npm
8+
9+
```npm
10+
npm i jsonfromtable
11+
```
12+
13+
You can convert

index.js

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ const toJson = require('./utils/tojson')
66
const defaultOptions = {
77
url: undefined,
88
html: undefined,
9-
selector: 'table'
9+
selector: 'table',
10+
format: 'jsobject'
1011
}
1112

12-
const html = async (options, headers) => {
13-
const { url, html, selector } = { ...defaultOptions, ...options }
13+
const htmlTableToJson = async (options, headers) => {
14+
const { url, html, selector, format } = { ...defaultOptions, ...options }
1415

1516
let data
1617

@@ -23,27 +24,26 @@ const html = async (options, headers) => {
2324

2425
const $ = cheerio.load(data)
2526

26-
let body = toJson($, 'table', headers)
27+
if ($('table').html() === null) {
28+
throw new Error(
29+
`Please provide ${url ? 'url' : 'html'} which contains table`
30+
)
31+
}
32+
33+
let body = toJson($, selector, headers)
2734

28-
console.log(body)
35+
if (format === 'json') {
36+
return JSON.stringify(body)
37+
} else {
38+
return body
39+
}
2940
}
3041

31-
html(
32-
{
33-
html: `
34-
<table style="width:100%">
35-
<tr>
36-
<td>Jill</td>
37-
<td>Smith</td>
38-
<td>50</td>
39-
</tr>
40-
<tr>
41-
<td>Eve</td>
42-
<td>Jackson</td>
43-
<td>94</td>
44-
</tr>
45-
</table>
46-
`
47-
},
48-
['Name', 'LastName', 'Age']
49-
)
42+
htmlTableToJson({
43+
url: 'https://www.worldometers.info/coronavirus/',
44+
format: 'json'
45+
}).then(data => {
46+
console.log(data)
47+
})
48+
49+
module.exports = htmlTableToJson

utils/tojson.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@ const toJson = ($, tableSelector, _header) => {
33
const body = []
44
let header = []
55

6+
if ($(tableSelector).html() === null) {
7+
throw new Error(
8+
`${tableSelector} is not a valid selector for table, please try again`
9+
)
10+
}
11+
612
// Add headers from table to header array
713
$(`${tableSelector} th`).each((_, el) => {
814
header.push(
@@ -26,7 +32,7 @@ const toJson = ($, tableSelector, _header) => {
2632
let d = {},
2733
j = 0
2834

29-
// For tds in table
35+
// loop all tds in table
3036
$(`${tableSelector} td`).each((_, el) => {
3137
let val = $(el)
3238
.text()

0 commit comments

Comments
 (0)