Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A JavaScript library for working with Table Schema.

License

NotificationsYou must be signed in to change notification settings

frictionlessdata/tableschema-js

Repository files navigation

BuildCoverageRegistryCodebaseSupport

A library for working withTable Schema.

Features

  • Table class for working with data and schema
  • Schema class for working with schemas
  • Field class for working with schema fields
  • validate function for validating schema descriptors
  • infer function that creates a schema based on a data sample

Contents

Getting started

To use the library withwebpack please replicate thewebpack.config.js->node configuration -https://github.com/frictionlessdata/tableschema-js/blob/master/webpack.config.js

Installation

The package use semantic versioning. It means that major versions could include breaking changes. It's highly recommended to specifytableschema version range in yourpackage.json file e.g.tabulator: ^1.0 which will be added by default bynpm install --save.

NPM

$ npm install tableschema

CDN

<scriptsrc="//unpkg.com/tableschema/dist/tableschema.min.js"></script>

Documentation

Introduction

Let's start with a simple example for Node.js:

const{Table}=require('tableschema')consttable=awaitTable.load('data.csv')awaittable.infer()// infer a schemaawaittable.read({keyed:true})// read the dataawaittable.schema.save()// save the schemaawaittable.save()// save the data

And for browser:

https://jsfiddle.net/rollninja/ayngwd38/2/

After the script registration the library will be available as a global variabletableschema:

<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"><title>tableschema-js</title></head><body><scriptsrc="//unpkg.com/tableschema/dist/tableschema.min.js"></script><script>constmain=async()=>{consttable=awaittableschema.Table.load('https://raw.githubusercontent.com/frictionlessdata/datapackage-js/master/data/data.csv')constrows=awaittable.read()document.body.innerHTML+=`<div>${table.headers}</div>`for(constrowofrows){document.body.innerHTML+=`<div>${row}</div>`}}main()</script></body></html>

Working with Table

A table is a core concept in a tabular data world. It represents data with metadata (Table Schema). Let's see how we could use it in practice.

Consider we have some local csv file. It could be inline data or remote link - all supported byTable class (except local files for in-browser usage of course). But say it'sdata.csv for now:

city,locationlondon,"51.50,-0.11"paris,"48.85,2.30"rome,N/A

Let's create and read a table. We use staticTable.load method andtable.read method with akeyed option to get array of keyed rows:

consttable=awaitTable.load('data.csv')table.headers// ['city', 'location']awaittable.read({keyed:true})// [//   {city: 'london', location: '51.50,-0.11'},//   {city: 'paris', location: '48.85,2.30'},//   {city: 'rome', location: 'N/A'},// ]

As we could see our locations are just strings. But it should be geopoints. Also Rome's location is not available but it's also just aN/A string instead of JavaScriptnull. First we have to infer Table Schema:

awaittable.infer()table.schema.descriptor// { fields://   [ { name: 'city', type: 'string', format: 'default' },//     { name: 'location', type: 'geopoint', format: 'default' } ],//  missingValues: [ '' ]}awaittable.read({keyed:true})// Fails with a data validation error

Let's fix not available location. There is amissingValues property in Table Schema specification. As a first try we setmissingValues toN/A intable.schema.descriptor. Schema descriptor could be changed in-place but all changes should be committed bytable.schema.commit():

table.schema.descriptor['missingValues']='N/A'table.schema.commit()table.schema.valid// falsetable.schema.errors// Error: Descriptor validation error://   Invalid type: string (expected array)//    at "/missingValues" in descriptor and//    at "/properties/missingValues/type" in profile

As a good citizens we've decided to check out schema descriptor validity. And it's not valid! We should use an array formissingValues property. Also don't forget to have an empty string as a missing value:

table.schema.descriptor['missingValues']=['','N/A']table.schema.commit()table.schema.valid// true

All good. It looks like we're ready to read our data again:

awaittable.read({keyed:true})// [//   {city: 'london', location: [51.50,-0.11]},//   {city: 'paris', location: [48.85,2.30]},//   {city: 'rome', location: null},// ]

Now we see that:

  • locations are arrays with numeric latitude and longitude
  • Rome's location is a native JavaScriptnull

And because there are no errors on data reading we could be sure that our data is valid against our schema. Let's save it:

awaittable.schema.save('schema.json')awaittable.save('data.csv')

Ourdata.csv looks the same because it has been stringified back tocsv format. But now we haveschema.json:

{"fields": [        {"name":"city","type":"string","format":"default"        },        {"name":"location","type":"geopoint","format":"default"        }    ],"missingValues": ["","N/A"    ]}

If we decide to improve it even more we could update the schema file and then open it again. But now providing a schema path and iterating thru the data using Node Streams:

consttable=awaitTable.load('data.csv',{schema:'schema.json'})conststream=awaittable.iter({stream:true})stream.on('data',(row)=>{// handle row ['london', [51.50,-0.11]] etc// keyed/extended/cast supported in a stream mode too})

It was only basic introduction to theTable class. To learn more let's take a look onTable class API reference.

Working with Schema

A model of a schema with helpful methods for working with the schema and supported data. Schema instances can be initialized with a schema source as a url to a JSON file or a JSON object. The schema is initially validated (seevalidate below). By default validation errors will be stored inschema.errors but in a strict mode it will be instantly raised.

Let's create a blank schema. It's not valid becausedescriptor.fields property is required by theTable Schema specification:

constschema=awaitSchema.load({})schema.valid// falseschema.errors// Error: Descriptor validation error://         Missing required property: fields//         at "" in descriptor and//         at "/required/0" in profile

To not create a schema descriptor by hands we will use aschema.infer method to infer the descriptor from given data:

schema.infer([['id','age','name'],['1','39','Paul'],['2','23','Jimmy'],['3','36','Jane'],['4','28','Judy'],])schema.valid// trueschema.descriptor//{ fields://   [ { name: 'id', type: 'integer', format: 'default' },//     { name: 'age', type: 'integer', format: 'default' },//     { name: 'name', type: 'string', format: 'default' } ],//  missingValues: [ '' ]}

Now we have an inferred schema and it's valid. We could cast data row against our schema. We provide a string input by an output will be cast correspondingly:

schema.castRow(['5','66','Sam'])// [ 5, 66, 'Sam' ]

But if we try provide some missing value toage field cast will fail because for now only one possible missing value is an empty string. Let's update our schema:

schema.castRow(['6','N/A','Walt'])// Cast errorschema.descriptor.missingValues=['','N/A']schema.commit()schema.castRow(['6','N/A','Walt'])// [ 6, null, 'Walt' ]

We could save the schema to a local file. And we could continue the work in any time just loading it from the local file:

awaitschema.save('schema.json')constschema=awaitSchema.load('schema.json')

It was only basic introduction to theSchema class. To learn more let's take a look onSchema class API reference.

Working with Field

Class represents a field in the schema.

Data values can be cast to native JavaScript types. Casting a value will check the value is of the expected type, is in the correct format, and complies with any constraints imposed by a schema.

{'name':'birthday','type':'date','format':'default','constraints':{'required':True,'minimum':'2015-05-30'}}

Following code will not raise the exception, despite the fact our date is less than minimum constraints in the field, because we do not check constraints of the field descriptor

vardateType=field.castValue('2014-05-29')

And following example will raise exception, because we set flag 'skip constraints' tofalse, and our date is less than allowed byminimum constraints of the field. Exception will be raised as well in situation of trying to cast non-date format values, or empty values

try{vardateType=field.castValue('2014-05-29',false)}catch(e){// uh oh, something went wrong}

Values that can't be cast will raise anError exception.Casting a value that doesn't meet the constraints will raise anError exception.

Available types, formats and resultant value of the cast:

TypeFormatsCasting result
anydefaultAny
arraydefaultArray
booleandefaultBoolean
datedefault, any, <PATTERN>Date
datetimedefault, any, <PATTERN>Date
durationdefaultmoment.Duration
geojsondefault, topojsonObject
geopointdefault, array, object[Number, Number]
integerdefaultNumber
numberdefaultNumber
objectdefaultObject
stringdefault, uri, email, binaryString
timedefault, any, <PATTERN>Date
yeardefaultNumber
yearmonthdefault[Number, Number]

Working with validate/infer

validate() validates whether aschema is a validate Table Schema accordingly to thespecifications. It doesnot validate data against a schema.

Given a schema descriptorvalidate returnsPromise with a validation object:

const{validate}=require('tableschema')const{valid, errors}=awaitvalidate('schema.json')for(consterroroferrors){// inspect Error objects}

Given data source and headersinfer will return a Table Schema as a JSON object based on the data values.

Given the data file, example.csv:

id,age,name1,39,Paul2,23,Jimmy3,36,Jane4,28,Judy

Callinfer with headers and values from the datafile:

constdescriptor=awaitinfer('data.csv')

Thedescriptor variable is now a JSON object:

{fields:[{name:'id',title:'',description:'',type:'integer',format:'default'},{name:'age',title:'',description:'',type:'integer',format:'default'},{name:'name',title:'',description:'',type:'string',format:'default'}]}

API Reference

Table

Table representation

table.headers ⇒Array.<string>

Headers

Returns:Array.<string> - data source headers

table.schema ⇒Schema

Schema

Returns:Schema - table schema instance

table.iter(keyed, extended, cast, forceCast, relations, stream) ⇒AsyncIterator |Stream

Iterate through the table data

And emits rows cast based on table schema (async for loop).With astream flag instead of async iterator a Node stream will be returned.Data casting can be disabled.

Returns:AsyncIterator |Stream - async iterator/stream of rows:

  • [value1, value2] - base

  • {header1: value1, header2: value2} - keyed

  • [rowNumber, [header1, header2], [value1, value2]] - extendedThrows:

  • TableSchemaError raises any error occurred in this process

ParamTypeDescription
keyedbooleaniter keyed rows
extendedbooleaniter extended rows
castbooleandisable data casting if false
forceCastbooleaninstead of raising on the first row with cast error return an error object to replace failed row. It will allow to iterate over the whole data file even if it's not compliant to the schema. Example of output stream:[['val1', 'val2'], TableSchemaError, ['val3', 'val4'], ...]
relationsObjectobject of foreign key references in a form of{resource1: [{field1: value1, field2: value2}, ...], ...}. If provided foreign key fields will checked and resolved to its references
streambooleanreturn Node Readable Stream of table rows

table.read(limit) ⇒Array.<Array> |Array.<Object>

Read the table data into memory

The API is the same astable.iter has except for:

Returns:Array.<Array> |Array.<Object> - list of rows:

  • [value1, value2] - base
  • {header1: value1, header2: value2} - keyed
  • [rowNumber, [header1, header2], [value1, value2]] - extended
ParamTypeDescription
limitintegerlimit of rows to read

table.infer(limit) ⇒Object

Infer a schema for the table.

It will infer and set Table Schema totable.schema based on table data.

Returns:Object - Table Schema descriptor

ParamTypeDescription
limitnumberlimit rows sample size

table.save(target) ⇒Boolean

Save data source to file locally in CSV format with, (comma) delimiter

Returns:Boolean - true on successThrows:

  • TableSchemaError an error if there is saving problem
ParamTypeDescription
targetstringpath where to save a table data

Table.load(source, schema, strict, headers, parserOptions) ⇒Table

Factory method to instantiateTable class.

This method is async and it should be used with await keyword or as aPromise.Ifreferences argument is provided foreign keys will be checkedon any reading operation.

Returns:Table - data table class instanceThrows:

  • TableSchemaError raises any error occurred in table creation process
ParamTypeDescription
sourcestring |Array.<Array> |Stream |functiondata source (one of): - local CSV file (path) - remote CSV file (url) - array of arrays representing the rows - readable stream with CSV file contents - function returning readable stream with CSV file contents
schemastring |Objectdata schema in all forms supported bySchema class
strictbooleanstrictness option to pass toSchema constructor
headersnumber |Array.<string>data source headers (one of): - row number containing headers (source should contain headers rows) - array of headers (source should NOT contain headers rows)
parserOptionsObjectoptions to be used by CSV parser. All options listed athttps://csv.js.org/parse/options/. By defaultltrim is true according to the CSV Dialect spec.

Schema

Schema representation

schema.valid ⇒Boolean

Validation status

It alwaystrue in strict mode.

Returns:Boolean - returns validation status

schema.errors ⇒Array.<Error>

Validation errors

It always empty in strict mode.

Returns:Array.<Error> - returns validation errors

schema.descriptor ⇒Object

Descriptor

Returns:Object - schema descriptor

schema.primaryKey ⇒Array.<string>

Primary Key

Returns:Array.<string> - schema primary key

schema.foreignKeys ⇒Array.<Object>

Foreign Keys

Returns:Array.<Object> - schema foreign keys

schema.fields ⇒Array.<Field>

Fields

Returns:Array.<Field> - schema fields

schema.fieldNames ⇒Array.<string>

Field names

Returns:Array.<string> - schema field names

schema.getField(fieldName) ⇒Field |null

Return a field

Returns:Field |null - field instance if exists

ParamType
fieldNamestring

schema.addField(descriptor) ⇒Field

Add a field

Returns:Field - added field instance

ParamType
descriptorObject

schema.removeField(name) ⇒Field |null

Remove a field

Returns:Field |null - removed field instance if exists

ParamType
namestring

schema.castRow(row, failFalst) ⇒Array.<Array>

Cast row based on field types and formats.

Returns:Array.<Array> - cast data row

ParamTypeDescription
rowArray.<Array>data row as an array of values
failFalstboolean

schema.infer(rows, headers) ⇒Object

Infer and setschema.descriptor based on data sample.

Returns:Object - Table Schema descriptor

ParamTypeDescription
rowsArray.<Array>array of arrays representing rows
headersinteger |Array.<string>data sample headers (one of): - row number containing headers (rows should contain headers rows) - array of headers (rows should NOT contain headers rows) - defaults to 1

schema.commit(strict) ⇒Boolean

Update schema instance if there are in-place changes in the descriptor.

Returns:Boolean - returns true on success and false if not modifiedThrows:

  • TableSchemaError raises any error occurred in the process
ParamTypeDescription
strictbooleanalterstrict mode for further work

Example

constdescriptor={fields:[{name:'field',type:'string'}]}constschema=awaitSchema.load(descriptor)schema.getField('name').type// stringschema.descriptor.fields[0].type='number'schema.getField('name').type// stringschema.commit()schema.getField('name').type// number

schema.save(target) ⇒boolean

Save schema descriptor to target destination.

Returns:boolean - returns true on successThrows:

  • TableSchemaError raises any error occurred in the process
ParamTypeDescription
targetstringpath where to save a descriptor

Schema.load(descriptor, strict) ⇒Schema

Factory method to instantiateSchema class.

This method is async and it should be used with await keyword or as aPromise.

Returns:Schema - returns schema class instanceThrows:

  • TableSchemaError raises any error occurred in the process
ParamTypeDescription
descriptorstring |Objectschema descriptor: - local path - remote url - object
strictbooleanflag to alter validation behaviour: - if false error will not be raised and all error will be collected inschema.errors - if strict is true any validation error will be raised immediately

Field

Field representation

new Field(descriptor, missingValues)

Constructor to instantiateField class.

Returns:Field - returns field class instanceThrows:

  • TableSchemaError raises any error occured in the process
ParamTypeDescription
descriptorObjectschema field descriptor
missingValuesArray.<string>an array with string representing missing values

field.name ⇒string

Field name

field.type ⇒string

Field type

field.format ⇒string

Field format

field.required ⇒boolean

Return true if field is required

field.constraints ⇒Object

Field constraints

field.descriptor ⇒Object

Field descriptor

field.castValue(value, constraints) ⇒any

Cast value

Returns:any - cast value

ParamTypeDescription
valueanyvalue to cast
constraintsObject |false

field.testValue(value, constraints) ⇒boolean

Check if value can be cast

ParamTypeDescription
valueanyvalue to test
constraintsObject |false

validate(descriptor) ⇒Object

This function is async so it has to be used withawait keyword or as aPromise.

Returns:Object - returns{valid, errors} object

ParamTypeDescription
descriptorstring |Objectschema descriptor (one of): - local path - remote url - object

infer(source, headers, options) ⇒Object

This function is async so it has to be used withawait keyword or as aPromise.

Returns:Object - returns schema descriptorThrows:

  • TableSchemaError raises any error occured in the process
ParamTypeDescription
sourcestring |Array.<Array> |Stream |functiondata source (one of): - local CSV file (path) - remote CSV file (url) - array of arrays representing the rows - readable stream with CSV file contents - function returning readable stream with CSV file contents
headersArray.<string>array of headers
optionsObjectanyTable.load options

DataPackageError

Base class for the all DataPackage/TableSchema errors.

If there are more than one error you could get an additional informationfrom the error object:

try{// some lib action}catch(error){console.log(error)// you have N cast errors (see error.errors)if(error.multiple){for(consterroroferror.errors){console.log(error)// cast error M is ...}}}

new DataPackageError(message, errors)

Create an error

ParamTypeDescription
messagestring
errorsArray.<Error>nested errors

dataPackageError.multiple ⇒boolean

Whether it's nested

dataPackageError.errors ⇒Array.<Error>

List of errors

TableSchemaError

Base class for the all TableSchema errors.

Contributing

The project follows theOpen Knowledge International coding standards. There are common commands to work with the project:

$ npm install$ npm runtest$ npm run build

Changelog

Here described only breaking and the most important changes. The full changelog and documentation for all released versions could be found in nicely formattedcommit history.

v1.12

  • Added support for infinite numbers: NaN, INF, -INF

v1.11

  • Improved data/time validation using a conversion table and moment.js (#170)

v1.10

  • Rebased on csv-parse@4

v1.9

Fix bug:

  • URI format must have the scheme protocol to be valid (#135)

v1.8

Improved behaviour:

  • Automatically detect the CSV delimiter if one isn't explicit set

v1.7

New API added:

  • addedforceCast flag to the thetable.iter/read methods

v1.6

Improved behaviour:

  • improved validation ofstring andgeojson types
  • added heuristics to theinfer function

v1.5

New API added:

  • addedformat option to theTable constructor
  • addedencoding option to theTable constructor

v1.4

Improved behaviour:

  • Now theinfer functions support formats inferring

v1.3

New API added:

  • error.rowNumber if available
  • error.columnNumber if available

v1.2

New API added:

  • Table.load andinfer now accept Node Stream as asource argument

v1.1

New API added:

  • Table.load andinfer now acceptsparserOptions

v1.0

This version includes various big changes, including a move to asynchronous inference.

v0.2

First stable version of the library.

About

A JavaScript library for working with Table Schema.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors23

Languages


[8]ページ先頭

©2009-2025 Movatter.jp