An open API service indexing awesome lists of open source software.

https://github.com/coderosh/jsonfromtable

Convert html tables to object (or array). Supports complex rowspan and colspan.
https://github.com/coderosh/jsonfromtable

json-from-table table-to-json

Last synced: 7 months ago
JSON representation

Convert html tables to object (or array). Supports complex rowspan and colspan.

Awesome Lists containing this project

README

          

banner


Convert html tables to object (or array). Supports complex rowspan and colspan.


NPM
MIT
CI
PRs welcome!
Typescript

## Installation

Install via npm

```sh
npm install jsonfromtable
```

Or via yarn

```sh
yarn add jsonfromtable
```

## Usage

### From html string

- Get array of objects with title as keys

```js
const { JSONFromTable } = require('jsonfromtable')

const obj = JSONFromTable.fromString(`...`)
console.log(obj)
/*
[
{
title: value1,
title2: value2,
...
},
...
]
*/
```

- Get array of title and body

```js
const { JSONFromTable } = require('jsonfromtable')

const { headers, body } = JSONFromTable.arrayFromString(`...`)
console.log(headers) // [title1, title2, title3, ...]
console.log(body) // [ [val1, val2, ...], [val3, val4, ...], ... ]
```

### From url

```js
const { JSONFromTable } = require('jsonfromtable')

async function main() {
const obj = await JSONFromTable.fromUrl(`https://...`)
console.log(obj)

const { headers, body } = await JSONFromTable.arrayFromUrl(`https://...`)
console.log(headers)
console.log(body)
}

main()
```


Each function in `JSONFromTable` accepts two arguments. First is source (html string or url) and second is `options`.

```ts
interface Options {
titles?: string[] // custom titles (eg: ["sn", "name", "title"])
firstRowIsHeading?: boolean // use first row for titles ?
includeFirstRowInBody?: boolean // add first row in body ?
tableSelector?: string // css selector for table (eg: table.wikitable)
rowColSelector?: [string, string] // css selectors for row and col (eg: ["tr", "th,td"])
shouldBeText?: boolean // if false value is html else true
trim?: boolean // should trim the value ?
}
```

## Example

```js
const str = `

name
alias
class
info


Roshan
Eng
na


John
Cook


Danger
Ninja


AGuy
Eng
Eats a lot


Dante
Art


Jake
ake
Actor

`

const obj = JSONFromTable.fromString(str, {
tableSelector: 'table',
trim: true,
})

console.log(obj)
```

## License

MIT