Skip to content

API Reference

Xavier Badosa edited this page Aug 20, 2015 · 75 revisions

WikiAPI Reference

Methods

By type

By hierarchy

		<li>
			Dataset responses: <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#class">class</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#length">length</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#id">id</a>,
			<a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#label">label</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#n">n</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#value">value</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#status">status</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#updated">updated</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#source">source</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#role">role</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#note">note</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#href">href</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#link">link</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#extension">extension</a>
			<ul>
				<li><strong><a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#dimension">Dimension()</a></strong>: <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#class">class</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#length">length</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#id">id</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#label">label</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#role">role</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#hierarchy">hierarchy</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#note">note</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#href">href</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#link">link</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#extension">extension</a>
					<ul>
						<li><strong><a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#category">Category()</a></strong>: <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#length">length</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#id">id</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#label">label</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#coordinates">coordinates</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#unit">unit</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#note">note</a></li>
					</ul>
				</li>
				<li><strong><a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#data">Data()</a></strong>: <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#value">value</a>, <a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#status">status</a></li>
				<li><strong><a href="https://github.com/badosa/JSON-stat/wiki/API-Reference#totable">toTable()</a></strong>
			</ul>
		</li>
	</ul>
</li>

Public Properties

class, coordinates, error, extension, hierarchy, href, id, label, length, link, n, note, role, source, status, unit, updated, value, version


Reading

JSONstat()


Parent: none
Description: Creates an internal jsonstat object from an external input in the JSON-stat format
Public Properties: class, length, id, error, label, n, value, status, updated, source, role, note, href, link, extension
Summary: object JSONstat ( object or string resp [, function callback] )
***

Parameters

resp (required)

It can be an object in the JSON-stat format or a string representing a URL.

var j=JSONstat( {...} );
if( j.length ){
		...
	}else{
		window.alert( "Wrong response!" );
	}
} );

When a URL is specified, JSONstat will try to connect to it to retrieve an object in the JSON-stat format. The JSONstat connection capabilities are limited to modern browsers: if you need to support very old browsers, use an object in the JSON-stat format instead of a URL string.

When the URL is absolute, JSONstat will attempt a cross-domain http request. This requires CORS support on the provider’s server. To avoid possible connection issues in older browsers, use a relative URL whenever possible.

If no callback is specified (deprecated), the connection will be synchronous.

var j=JSONstat( "http://json-stat.org/samples/oecd-ds.json" );
if( j.length ){
	...
}else{
	window.alert( "Wrong response!" );
}
callback

It is a function.

When callback is specified and resp is not an object, the connection is asynchronous. callback is executed after the connection has successfully finished and the resulting object of class jsonstat is assigned to the this keyword.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if( this.length ){
		...
	}else{
		window.alert( "Wrong response!" );
	}
} );

If resp is an object, callback is ignored.

Returned Value

It returns a jsonstat object. When callback is specified, the object returned by JSONstat will be empty (the actual object is only accessible inside the callback function, in the this keyword).

The public properties of this object depend on the value of the class property.

Common properties: class, length, id

Additional properties when class is "collection": label, updated, source, note, href, link, extension

Additional properties when class is "bundle": error

Additional properties when class is "dataset": label, n, value, status, updated, source, role, note, href, link, extension

Traversing

Dataset()


Parent: JSONstat
Description: Gets dataset information from an internal jsonstat object with class "bundle" (for generalization's sake, it can also be applied to objects with class "dataset")
Public Properties: class, length, id, label, n, value, status, updated, source, role, note, href, link, extension
Summary: object or array Dataset ( [integer or string dsid] )
***

Parameters

dsid

It can be a positive integer (access by index in the datasets id array) or a string (access by ID).

Returned Value

When a valid dsid is specified, it returns a jsonstat object. If dsid is not valid, a null is returned. If dsid is not specified, it will return an array of jsonstat objects: one for each dataset.

JSONstat( "http://json-stat.org/samples/oecd-canada.json" , function() {
	if( this.class==="bundle" ){
		var ds1=this.Dataset( 0 );
	}
} );
JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if( this.class==="dataset" ){
		window.alert( this===this.Dataset( 0 ) ); //true
	}
} );

Dimension()


Parent: Dataset
Description: Gets dimension information from an internal jsonstat object
Public Properties: class, length, id, label, role, hierarchy, note, href, link, extension
Summary: object or array Dimension ( [integer, string or object dimid] )
***

Parameters

dimid

It can be a positive integer (access by index in the dimensions id array) or a string (access by ID). If no dimid is specified, it will return information for every dimension.

It can also be an object in the form { role : string }, where string is time, geo, metric or classification. This syntax is used to filter dimensions with a particular role.

Returned Value

When a valid dimid is specified, it returns a jsonstat object. If dimid is not valid, a null is returned. If dimid is not specified, it returns an array of jsonstat objects: one for each dimension. If dimid is a valid object, it returns an array of jsonstat objects: one for each dimension with the selected role.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if( this.class==="dataset" ){
		//Label of the first dimension
		var label1=this.Dimension( 0 ).label;
	}
} );
JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Label of the first dimension with role "geo"
	var geolabel1=this.Dimension( {role: "geo"} )[0].label;
} );

Category()


Parent: Dimension
Description: Gets category information from an internal jsonstat object
Public Properties: length, id, label, coordinates, unit, note
Summary: object or array Dimension ( [integer or string catid] )
***

Parameters

catid

It can be a positive integer (access by index in the categories id array) or a string (access by ID).

Returned Value

When a valid catid is specified, it returns a jsonstat object. If catid is not valid, a null is returned. If catid is not specified, it will return an array of jsonstat objects: one for each category.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Label of category "AU" in dimension "area"
	var AUlabel=this.Dimension( "area" ).Category( "AU" ).label; //"Australia"
} );

Data()


Parent: Dataset
Description: Gets data information from an internal jsonstat object
Public Properties: value, status
Summary: object or array Data ( [integer, array or object dataid] )
***

Parameters

dataid

It can be a positive integer (by index in the value array), an array (by dimensions indices) or an object (by dimensions IDs).

Returned Value

The returned value can be a value-status object (that is, an object with two properties: value and status), an array of value-status objects or null when dataid is not valid.

If dataid is not specified, the result is an array of value-status objects (one object per datum in the dataset).

If dataid is an integer, the result is a value-status object if dataid is a valid index. Otherwise, a null is returned.

If dataid is an array, the result is a value-status object if dataid has the correct size (number of dimensions) and valid category indices. Otherwise, a null is returned.

If dataid is an object, a dimension is ignored if its ID or the ID of its category is invalid. If all dimensions/categories are correctly specified, the result is a value-status object. Take into account that constant dimensions (that is, single category dimensions) are not required. Therefore, to get a value-status object, you need to validly select a category for all the non-constant dimensions. If you do not validly select a category of a non-constant dimension (from now on, the free dimension), the returned value will be an array of value-status objects: one for each category in the free dimension (slice). Objects will be ordered in the free dimension category order. If there is more than one free dimension, a null will be returned.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Value of the first observation
	var data0=this.Data( 0 ).value;
	//Same as value with the first category in each dimension
	var data000=this.Data( [0, 0, 0] ).value;
	//Value with concept "UNR", area "GR" and year "2014"
	var unrGR2014=this.Data( {"concept": "UNR", "area": "GR", "year": "2014"} ).value;
} );

Transforming

toTable()


Parent: Dataset
Description: Converts information from an internal jsonstat object into tabular form
Public Properties: —
Summary: object or array toTable ( [object opts, function callback] )
***

Parameters

opts

It is an object with the following optional properties:

  • type: String (arrobj, object, array). Default value is array. It determines the form of the returned value.
  • status: Boolean. Default value is false. It determines whether the status of each value is included in the returned value.
  • content: String (id, label). Default value is label. It determines whether categories are identified in the returned value by label or by ID.
  • field: String (id, label). Default value is label. Only available when type is object or array. It determines whether dimensions, value and status are identified in the returned value by label or by ID.
  • vlabel: String. Default value is Value. Only available when type is object or array. It determines the label of the value field.
  • slabel: String. Default value is Status. Only available when type is object or array and status is true. It determines the label of the status field.
JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//Column names (first row)
	//["country", "year", "age group", "concepts", "sex", "Value"]
	var cols=this.toTable( {type: "array"} )[0];
	//IDs instead of labels
	//["country", "year", "age", "concept", "sex", "value"]
	cols=this.toTable( {type: "array", field: "id"} )[0];
	//Labels including status
	//["country", "year", "age group", "concepts", "sex", "Status", "Value"]
	cols=this.toTable( {type: "array", status: true} )[0];
	//Same but naming status as "Metadata" and value as "Data"
	cols=this.toTable( {type: "array", status: true, vlabel: "Data", slabel: "Metadata"} )[0];
	//First data row
	//["Canada", "2012", "total", "population", "total", 34880.5]
	var row1=this.toTable( {type: "array"} )[1];
	//Same including status
	//["Canada", "2012", "total", "population", "total", "a", 34880.5]
	row1=this.toTable( {type: "array", status: true} )[1];
	//Same but IDs instead of labels
	//["CA", "2012", "T", "POP", "T", "a", 34880.5]
	row1=this.toTable( {type: "array", status: true, content: "id"} )[1];
} );
callback

It is a function used to transform the returned value.

Even though toTable can expose a table using different structures depending on type, it always includes some sort of array for data. callback will be invoked for each element of the data array, passing two parameters: the element and its index. The this keyword in callback is the dataset information as a jsonstat object.

JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//Discard data by age in the resulting table
	this.toTable(
	   { type : "arrobj" },
	   function( d, i ){
	      if( d.age === "total" ){
	         return d;
	      }
	   }
	);
} );

Filters and transformations in the callback must be expressed in terms of the form of the data array, which depends on opts. In the previous example, age is filtered using a category label (Total) because this is the default value of the content option.

JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//Discard data by age in the resulting table.
	//Using categories ID instead of labels.
	this.toTable(
	   { type : "arrobj" , content : "id" },
	   function( d, i ){
	      if( d.age === "T" ){
	         return d;
	      }
	   }
	);
} );

Take into account that every type returns a different form of data array.

JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//As previous example but with type "array"
	//Age is the third dimension (its index is 2)
	this.toTable(
	   { type : "array" , content : "id" },
	   function( d, i ){
	      if( d[2] === "T" ){
	         return d;
	      }
	   }
	);
} );
JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//As previous example but with type "object"
	//Age is the third dimension (its index is 2)
	this.toTable(
	   { type : "object" , content : "id" },
	   function( d, i ){
	      if( d.c[2].v === "T" ){
	         return d;
	      }
	   }
	);
} );

The arrobj type does not return a table header, but array and object type do: callback cannot act on the header, only on the data array.

JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//This will not remove the header (row 0 in type "array") but the first data row
	this.toTable(
	   { type: "array" },
	   function( d, i ){
	      if( i ){
	         return d;
	      }
	   }
	);
} );

Because array and object type includes a header in the result, it is not advisable to change the structure of the data array when using these types: the header will be left untouched and incoherent.

If you need to transform the output deeply use the arrobj type.

JSONstat( "http://json-stat.org/samples/canada-ds.json" , function() {
	//Select only the female population by age group
	//Get an array of objects with only two properties (age and population)
	//Change scale of units
	this.toTable(
	   { type: "arrobj", content: "id" },
	   function( d ){
	      if( d.sex === "F" && d.concept === "POP" ){
	         return { age: d.age, population: d.value*1000 };
	      }
	   }
	);
} );

Returned Value

It depends on the type specified in the opts parameter.

arrobj type

It returns an array of objects, where the key is the dimension ID, value or status (columns) and the value can be the category label or ID.

[
   { "age" : "total", "concept" : "population", "country": "Canada", "sex": "total", "value" : 34880.5, "year" : "2012"},
	 { "age" : "total", "concept" : "population", "country": "Canada", "sex": "male", "value" : 17309.1, "year" : "2012"},
	 { "age" : "total", "concept" : "population", "country": "Canada", "sex": "female", "value" : 17571.3, "year" : "2012"},
   ...
]
array type

It returns an array of arrays. The first element in the array contains the column labels or IDs. The next elements can use category labels or IDs.

[
   [ "country", "year", "age group", "concepts", "sex", "Value" ],
   [ "Canada", "2012", "total", "population", "total", 34880.5 ],
   [ "Canada", "2012", "total", "population", "male", 17309.1 ],
	 ...
]
object type

It returns an object of arrays in the Google DataTable format.

{
   "cols" : [ ... ],
   "rows" : [ ... ]
}

Warning: DataTable declares explicitly the type of the values. JSON-stat does not, so this information must be inferred. Generally, it can safely be assumed that values are numbers. Currently, toTable only performs a very naïf test: if the first value is a number (or null), it will assign a type of number; otherwise, it will assign a type of string.

Item()


Parent: JSONstat
Description: Gets item information from an internal jsonstat object with class "collection"
Public Properties: class, href, label, extension
Summary: object or array Item ( [integer or object itemid] )
***

Parameters

itemid

It can be a positive integer (access to item information by index) or an object.

When itemid is an object, it must have a "class" property with a valid class value.

Returned Value

When a valid itemid is specified, it returns an item object (an object with the public properties of Item()). If itemid is an integer but out of range, a null is returned. If itemid has a "class" property, it will return an array of item objects: those that meet the filter conditions; otherwise, a null is returned. If the value of the "class" property is not a valid class value, an empty array is returned.

When itemid is not specified, it returns an array of item objects: one for each item.

JSONstat( "http://json-stat.org/samples/collection.json" , function() {
	//Get the label of the first item in the collection
	var label1=this.Item( 0 ).label;
} );
JSONstat( "http://json-stat.org/samples/collection.json" , function() {
	//Get the number of items with class "dataset" in the collection
	var dsn=this.Item( {class: "dataset"} ).length;
} );

Public Properties

class

Response class. String ("collection", "bundle", "dataset", "dimension").

var
  j=JSONstat( {...} ),
  datasets=[]
;
switch( j.class ){
  case "collection":
    j.Item( {class: "dataset"} ).forEach( function( e ){
      datasets.push( JSONstat( e.href ) ); //Async. Deprecated.
    } );
  break;
  case "bundle":
    datasets=j.Dataset();
  break;
  case "dataset":
    datasets=[j];
  break;
}

coordinates

Category coordinates if the category dimension has a geo role. Array of two numbers (longitude, latitude). If no coordinates have been provided, a null is returned.

error

Optional error information. Object. The properties of this object depend on the provider.

extension

Collection, dataset, dimension or item extended information. Object. The properties of this object depend on the provider.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
  var
		//This dataset contains extended properties
		ext=this.extension,
		//Get e-mail of contact
		email=ext["contact"]
	;
} );

hierarchy

True if there is information about the relationship between the categories in the dimension. Boolean.

JSONstat( "http://json-stat.org/samples/hierarchy-ds.json" , function() {
  //First dimension
  var dim=this.Dimension( 0 );
	if( dim.hierarchy ){
    var
      //First category ID
      id=dim.id[0],
      //Array of children's IDs
      ids=dim.Category( 0 ).id
    ;
  }
} );

href

Collection, bundle, dataset or dimension URL.

JSONstat( "http://json-stat.org/samples/collection.json" , function() {
	//Get the URL of the first item in the collection
	var href1=this.Item( 0 ).href;
} );

id

Datasets, dimensions, categories, category children or items IDs. Array of strings.

In the case of category children, id is an array when the dimension includes hierarchical information and the selected category has children. Otherwise it is null.

In the case of items, id is an array of URLs.

//This example would work also with http://json-stat.org/samples/oecd-ds.json
JSONstat( "http://json-stat.org/samples/oecd-canada.json" , function() {
  if( this.class==="bundle" || this.class==="dataset" ){
    var
      //"OECD" dataset (if class "bundle")
      ds=this.Dataset( "oecd" ),
      //Dimensions' IDs of that dataset
      dimids=ds.id,
      //"area" dimension in that dataset
      dim=ds.Dimension( "area" ),
      //Categories' IDs of that dimension
      catids=dim.id
    ;
    if( dim.hierarchy ){
      //Category IDs that belong to OECD
      var oecdids=dim.Category( "OECD" ).id;
    }
  }
} );

label

Collection, dataset, dimension, category or item label. String.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
  //Label for "AU" area (Australia)
  var label=this.Dataset( "oecd" ).Dimension( "area" ).Category( "AU" ).label;
} );

length

Number of datasets, dimensions, categories, category children or items. Integer.

You should always check for length>0 before further processing.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if( this.length ){
		...
	}else{
		window.alert( "Wrong response!" );
	}
} );

link

Collection, bundle, dataset or dimension links. Object of relation names.

JSONstat( "http://json-stat.org/samples/collection.json" , function() {
	//Get info for IANA link relation "item" in a collection http://www.iana.org/assignments/link-relations/link-relations.xhtml
	var items=this.link["item"];
	//Same as this.Item().
} );

n

Number of values in the dataset. Integer. It is the number of cells in the cube, even if they are empty (missing values).

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	window.alert("This dataset has "+this.n+" observations.");
} );

note

Dataset, dimension, category or collection annotations. Array of strings except category annotations, which are an object of strings.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Display general dataset annotations if available
	var note=this.note;
	if( note ){
		note.forEach(function(e){
			window.alert(e);
		});
	}
	//Display annotations for Germany if available
	var denote=this.Dimension( "area" ).Category( "DE" ).note;
	if( denote ){
		denote.forEach(function(e){
			window.alert(e);
		});
	}
} );

role

Dimensions with role time, geo, metric or with unspecified role (classification). Null if role information was not included in the response; otherwise, object with four keys (time, geo, metric and classification). The value of every key is an array of dimensions IDs (or null if no dimension has the specified role).

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Get the name of the first dimension with a "geo" role
	var geo1=this.role.geo[0];
} );

Dimension role. String (time, geo, metric; otherwise, classification) or null (when role information not included in the response).

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Role of the "concept" dimension
	var crole=this.Dimension( "concept" ).role;
} );

source

Dataset or collection source. String.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Dataset source
	var source=this.source;
} );

status

As a property of a dataset, status of its values. Array or null.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if(this.status){
		//Status of the 23rd value
		var status23=this.status[22];
	}
} );

As a property of a datum, status of its value. String or null if not provided.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Status of the 23rd value
	var status23=this.Data( 22 ).status;
} );

unit

Category unit information if the category dimension has a metric role. Object. Except "decimals", "label", "symbol" and "position", the rest of the properties of this object depend on the provider. If no unit information has been provided, a null is returned.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//Decimals of the first category in the first dimension with a "metric" role
	var dec=j.Dimension( {role: "metric"} )[0].Category( 0 ).unit.decimals;
} );

updated

It is the update date of the dataset or collection. String representing a date in an ISO 8601 format recognized by the Javascript Date.parse method.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if(this.updated){
		var
			upd=new Date(this.updated),
			timelapse=Date.now()-upd,
			days=Math.floor( timelapse / ( 1000*60*60*24 ) )
		;
		window.alert( "This dataset was updated "+String( days )+" days ago." );
	}
} );

value

As a property of a dataset, dataset values. Array.

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	if(this.value){
		//23rd value
		var value23=this.value[22];
	}
} );

As a property of a datum, datum value. Usually a number. Data() returns whatever was included in the cell by the provider (number, string, null...).

JSONstat( "http://json-stat.org/samples/oecd-ds.json" , function() {
	//23rd value
	var value23=this.Data( 22 ).value;
} );

version

Version of the JSON-stat Javascript Toolkit. String.

var ver=JSONstat.version;

Clone this wiki locally