### Item Method Usage Examples Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/api-reference.md Examples demonstrating how to use the Item method to retrieve all items, items by index, embedded datasets, and dataset references. ```javascript const collection = JSONstat(collectionData); // Get all items const allItems = collection.Item(); // Get by position const firstItem = collection.Item(0); // Get all embedded datasets const embeddedDsets = collection.Item({ class: "dataset", embedded: true }); // Get all dataset references const references = collection.Item({ class: "dataset", embedded: false }); ``` -------------------------------- ### Install jsonstat-toolkit via NPM Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Use npm to install the jsonstat-toolkit package for your project. ```bash npm install jsonstat-toolkit ``` -------------------------------- ### Example of Item Method Usage Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/types.md Shows how to use the Item method with a filter object to retrieve specific types of items from a collection. Examples include getting all embedded datasets and all dataset references. ```javascript const collection = JSONstat(data); // Get all embedded datasets const embedded = collection.Item({ class: "dataset", embedded: true }); // Get all dataset references const refs = collection.Item({ class: "dataset", embedded: false }); ``` -------------------------------- ### Node.js Installation for Older Versions Source: https://github.com/jsonstat/toolkit/blob/master/docs/INSTALL.md For older Node.js versions, install version 1.6.0 of the Toolkit, which includes the node-fetch module. This ensures compatibility with older environments. ```bash $ npm install jsonstat-toolkit@1.6.0 ``` -------------------------------- ### Install jsonstat version 0 for Legacy Support Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Install version 0 of the jsonstat package for compatibility with older browsers like IE6. ```bash npm install jsonstat@0 ``` -------------------------------- ### JSONstat Data Access Chain Example Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/module-structure.md Demonstrates how to chain methods to access specific data points within a JSONstat object, starting from a dataset and drilling down to a category or data value. ```plaintext json.Dataset(0) → new jsonstat() for dataset json.Dataset(0).Dimension("time") → new jsonstat() for dimension json.Dataset(0).Dimension("time").Category(0) → new jsonstat() for category json.Dataset(0).Data({time: "2021"}) → Returns { value, status } object ``` -------------------------------- ### Node.js Installation Source: https://github.com/jsonstat/toolkit/blob/master/docs/INSTALL.md Install the latest version of the JSON-stat Toolkit in your Node.js project using npm. Version 21+ of Node.js is recommended for stable Fetch API support. ```bash $ npm install jsonstat-toolkit ``` -------------------------------- ### JSON-stat 2.0 Dataset Example Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/json-stat-format.md A comprehensive example of a JSON-stat 2.0 dataset, including version, class, metadata, dimension definitions, values, and status codes. ```javascript { "version": "2.0", "class": "dataset", "label": "GDP by Country and Year", "source": "World Bank", "updated": "2023-01-15T10:30:00Z", "link": { "about": "https://example.com/datasets/gdp" }, "note": "Values in billions USD", "id": ["year", "country", "measure"], "size": [3, 2, 2], "dimension": { "year": { "label": "Year", "role": "time", "category": { "index": { "2020": 0, "2021": 1, "2022": 2 }, "label": { "2020": "2020", "2021": "2021", "2022": "2022" } } }, "country": { "label": "Country", "role": "geo", "category": { "index": { "US": 0, "JP": 1 }, "label": { "US": "United States", "JP": "Japan" }, "coordinates": { "US": { "lat": 39.8, "lon": -104.8 }, "JP": { "lat": 36.2, "lon": 138.2 } } } }, "measure": { "label": "Measure", "role": "metric", "category": { "index": { "GDP": 0, "PER_CAPITA": 1 }, "label": { "GDP": "GDP (total)", "PER_CAPITA": "GDP per capita" }, "unit": { "GDP": "billion USD", "PER_CAPITA": "USD" } } } }, "value": [ 21060, 67300, // 2020, US: GDP, GDP per capita 22997, 69288, // 2021, US 25477, 76398, // 2022, US 5108, 40800, // 2020, Japan 4230, 33700, // 2021, Japan 4236, 33800 // 2022, Japan ], "status": [ "o", "o", "p", "p", "e", "e", "o", "o", "p", "p", "e", "e" ] } ``` -------------------------------- ### Coordinates Object Example Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/types.md An example of a Coordinates object, showing how dimension IDs like 'time', 'geo', and 'metric' are mapped to their category IDs. ```javascript { time: "2021", geo: "US", metric: "GDP" } ``` -------------------------------- ### IE Support GET Request Version 1 Source: https://github.com/jsonstat/toolkit/blob/master/docs/EXAMPLES.md Include polyfills for Promises and Fetch, then include JSON-stat toolkit version 1 for GET requests, enabling support in older browsers like IE. ```html ``` -------------------------------- ### Example of Dice Method Usage Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/types.md Illustrates using the Dice method with different options. The first example clones the dataset and filters categories, while the second removes categories and returns a JSON string. ```javascript // Keep categories, get new dataset const filtered = dataset.Dice( { time: ["2020", "2021"] }, { clone: true } ); // Remove categories, get JSON string const jsonStr = dataset.Dice( { time: ["2022", "2023"] }, { drop: true, stringify: true } ); ``` -------------------------------- ### Dice Method Usage Examples Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/api-reference.md Examples demonstrating the Dice method for filtering datasets by keeping specific categories, dropping categories, and returning a JSON string. ```javascript const dataset = jsonstat.Dataset(0); // Keep only 2020 and 2021, US and UK const filtered = dataset.Dice({ time: ["2020", "2021"], geo: ["US", "UK"] }); // Drop a year const withoutRecent = dataset.Dice( { time: ["2022"] }, { drop: true } ); // Clone and return as JSON string const jsonString = dataset.Dice( { time: ["2020", "2021"] }, { clone: true, stringify: true } ); ``` -------------------------------- ### Dimension Metadata Object Example Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/types.md An example of a Dimension Metadata object, illustrating how dimension IDs are categorized by role. This is typically accessed via the Dataset.role property. ```javascript const dataset = json.Dataset(0); console.log(dataset.role); // { // time: ["year"], // geo: ["country"], // metric: ["GDP", "population"], // classification: null // } ``` -------------------------------- ### Example of Google DataTable Format Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/types.md Provides an example of data structured according to the Google DataTable format. This includes definitions for columns (id, label, type) and rows, where each row contains cells with values. ```javascript { cols: [ { id: "time", label: "Year", type: "string" }, { id: "geo", label: "Country", type: "string" }, { id: "value", label: "GDP", type: "number" } ], rows: [ { c: [{ v: "2020" }, { v: "US" }, { v: 10000 }] }, { c: [{ v: "2020" }, { v: "UK" }, { v: 3000 }] } ] } ``` -------------------------------- ### IE Support GET Request Version 0 Source: https://github.com/jsonstat/toolkit/blob/master/docs/EXAMPLES.md Include JSON-stat version 0 and use it for a GET request, suitable for older browsers like IE. ```html ``` -------------------------------- ### GET Request Version 1 Source: https://github.com/jsonstat/toolkit/blob/master/docs/EXAMPLES.md Perform a GET request to retrieve JSON-stat data using version 1 of the toolkit. The promise resolves with the JSON-stat instance. ```js JSONstat(url).then(main); function main(j){ var ds=j.Dataset(0); ... } ``` -------------------------------- ### Example of Transform Meta Object Usage Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/types.md Demonstrates how to use the Transform method with meta: true to retrieve dataset metadata. The output includes dataset properties and dimension details. ```javascript const result = dataset.Transform({ type: "arrobj", meta: true, status: true, by: "time" }); console.log(result.meta); // { // type: "arrobj", // label: "My Dataset", // id: ["country", "time"], // by: "time", // dimensions: { // country: { label: "Country", role: "geo", categories: {...} }, // time: { label: "Year", role: "time", categories: {...} } // } // } console.log(result.data); // Array of pivoted objects ``` -------------------------------- ### Item Filter Object Examples Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/api-reference.md Examples of filter objects used with the Item method to select specific items based on class and embedding. ```javascript { class: "dataset" } ``` ```javascript { class: "dataset", embedded: true } ``` ```javascript { class: "dataset", embedded: false } ``` -------------------------------- ### Unflatten() Examples Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Demonstrates various ways to use the Unflatten method to transform JSON-stat data into different array and CSV formats. ```APIDOC ## Unflatten() Examples ### Description Provides examples of using the `Unflatten` method to restructure JSON-stat data into arrays of objects or CSV strings. ### Method `JSONstat(...).then(function(j) { ... j.Unflatten(...) ... });` ### Parameters `Unflatten` accepts a callback function with the following parameters: - `coordinates` (object): An object mapping dimension IDs to category IDs for the current data point. - `datapoint` (object): An object representing the data point, typically containing 'value' and 'status'. - `n` (number): The index of the current row being processed. - `row` (array): The array representing the current row (used for CSV generation). ### Examples 1. **Array of objects with coordinates and datapoint**: ```js const arr1 = j.Unflatten((coordinates, datapoint) => { return { coordinates, datapoint }; }); ``` 2. **Array of objects with coordinates and value**: ```js const arr2 = j.Unflatten((coordinates, datapoint) => { return { coordinates, value: datapoint.value }; }); ``` 3. **Array of flat objects using dimension and category IDs**: ```js const arr3 = j.Unflatten((coordinates, datapoint) => { const ret = {}; j.id.forEach(dimId => { ret[dimId] = coordinates[dimId]; }); ret.value = datapoint.value; return ret; }); ``` 4. **Array of flat objects with dimension/category labels and status**: ```js const arr4 = j.Unflatten((coordinates, datapoint) => { const ret = {}; j.id.forEach(dimId => { const dim = j.Dimension(dimId); ret[dim.label] = dim.Category(coordinates[dimId]).label; }); ret.value = datapoint.value; ret.status = datapoint.status; return ret; }); ``` 5. **CSV string with value and status**: ```js const csv1 = j.Unflatten((coordinates, datapoint, n, row) => { const dimIds = j.id; const ret = {}; if (n === 0) { row.push(dimIds.join(',').concat(',value,status')); } dimIds.forEach(dimId => { ret[dimId] = coordinates[dimId]; }); ret.value = datapoint.value; ret.status = datapoint.status; return Object.values(ret).join(','); }).join('\n'); ``` 6. **Filtered CSV string (only females)**: ```js const csv2 = j.Unflatten((coordinates, datapoint, n, row) => { const dimIds = j.id; const ret = {}; if (n === 0) { row.push(dimIds.join(',').concat(',value,status')); } dimIds.forEach(dimId => { ret[dimId] = coordinates[dimId]; }); ret.value = datapoint.value; ret.status = datapoint.status; if (coordinates.sex === 'F') { return Object.values(ret).join(','); } }).join('\n'); ``` ``` -------------------------------- ### GET Request Version 0 Source: https://github.com/jsonstat/toolkit/blob/master/docs/EXAMPLES.md Perform a GET request to retrieve JSON-stat data using version 0 of the library. The callback function receives the JSON-stat instance. ```js JSONstat(url, main); function main(){ //"this" contains the jsonstat instance of the retrieved JSON var ds=this.Dataset(0); ... } ``` -------------------------------- ### Error Handling Example Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Catch and handle non-2xx HTTP responses by checking the error message for status codes. ```javascript JSONstat("https://example.com/missing.json") .catch(error => { if (error.message.includes("404")) { console.log("Data not found"); } }); ``` -------------------------------- ### Transform Data to Array Format Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Transforms the JSONstat dataset into a simple array format. The first example shows the default output, while subsequent examples demonstrate how to use options to change the field identifiers to IDs, include status information, and customize value and status labels. ```javascript JSONstat( "https://json-stat.org/samples/canada.json" ).then(function(j) { //Column names (first row) //["country", "year", "age group", "concepts", "sex", "Value"] var cols=j.Transform( { type : "array" } )[0]; ``` ```javascript //IDs instead of labels //["country", "year", "age", "concept", "sex", "value"] cols=j.Transform( { type : "array", field : "id" } )[0]; ``` ```javascript //Labels including status //["country", "year", "age group", "concepts", "sex", "Status", "Value"] cols=j.Transform( { type : "array", status : true } )[0]; ``` ```javascript //Same but naming status as "Metadata" and value as "Data" cols=j.Transform( { type : "array", status : true, vlabel : "Data", slabel: "Metadata" } )[0]; ``` -------------------------------- ### Handling Fetch and Data Format Errors Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md This example shows how to handle potential network errors during data fetching using .catch() and how to validate the fetched data's format by checking its 'class' property. ```javascript JSONstat("https://example.com/data.json") .then(data => { if (data.class === null) { console.log("Invalid JSON-stat format"); return; } // Process data }) .catch(error => { // Handle network/HTTP errors console.error("Failed to fetch:", error.message); }); ``` -------------------------------- ### Retrieving Dataset Source Information Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Get the source string for a dataset or collection. This is useful for attribution and understanding data provenance. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { //Dataset source var source=j.source; }); ``` -------------------------------- ### JSONstat Constructor to Get Package Version Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Retrieve the package version by passing the string 'version' to the JSONstat constructor. ```javascript JSONstat("version") // Returns "2.2.2" ``` -------------------------------- ### Retrieve JJT Version 1 Source: https://github.com/jsonstat/toolkit/blob/master/docs/EXAMPLES.md Get the version of the JSON-stat toolkit in version 1. ```js var version=JSONstat("version"); ``` -------------------------------- ### Retrieve JJT Version 0 Source: https://github.com/jsonstat/toolkit/blob/master/docs/EXAMPLES.md Get the version of the JSON-stat library in version 0. ```js var version=JSONstat.version; ``` -------------------------------- ### Safely Accessing Data Cells Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md This example shows how to safely access data cells using the Data() method and checking the returned cell object for null before accessing its properties like 'value' or 'status'. ```javascript // Check if value exists before accessing const cell = dataset.Data(0, true); if (cell !== null) { console.log(cell.value); // Safe console.log(cell.status); // Can be null } else { console.log("Cell not found"); } ``` -------------------------------- ### Load and Get Number of Items from URL Source: https://github.com/jsonstat/toolkit/blob/master/README.md Fetch a JSON-stat response from a URL and log the number of items it contains. This demonstrates asynchronous data loading and basic inspection. ```javascript JSONstat( "https://json-stat.org/samples/oecd-canada-col.json" ).then( function(J){ console.log( J.length ); } ) ``` -------------------------------- ### Transform Data with Callback (array type, no filtering) Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Demonstrates filtering with the 'array' type, which includes a header. This example filters the first data row (index 1) by checking the index 'i'. ```javascript JSONstat( "https://json-stat.org/samples/canada.json" ).then(function(j) { //This will not remove the header (row 0 in type "array") but the first data row const arr=j.toTable( { type : "array" }, function( d, i ){ if( i ){ return d; } } ); }); ``` -------------------------------- ### Instantiate JSONstat from Object, URL, or Version Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/api-reference.md Create a JSONstat instance from a JSON-stat formatted object, fetch a resource from a URL, or get the package version. For URLs, a Promise is returned. The TypedArray constructor can be optionally provided for value normalization. ```javascript const data = JSONstat({ version: "2.0", class: "dataset", dimension: { id: ["time", "geo"], size: [3, 2], time: { category: { index: { "2020": 0, "2021": 1, "2022": 2 }, label: { "2020": "2020", "2021": "2021", "2022": "2022" } } }, geo: { category: { index: { "US": 0, "UK": 1 }, label: { "US": "United States", "UK": "United Kingdom" } } } }, id: ["time", "geo"], size: [3, 2], value: [10, 20, 30, 40, 50, 60] }); JSONstat("https://json-stat.org/samples/oecd-canada-col.json").then(data => { console.log(data.length); // number of datasets }); JSONstat(jsonObject, Float32Array); ``` -------------------------------- ### Detect Data Access with Multiple Undefined Dimensions Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md This example demonstrates that if a data selector has multiple undefined dimensions, the access will fail and return null. Ensure at least one dimension is specified or defined. ```javascript // More than one dimension undefined dataset.Data([undefined, undefined, 0]) // null ``` -------------------------------- ### Get Dataset by Index from Bundle Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieves a dataset by its index from a JSONstat bundle instance. Ensure the instance is of class 'bundle' before calling. ```js JSONstat( "https://json-stat.org/samples/oecd-canada.json" ).then(function(j) { if( j.class==="bundle" ){ var ds1=j.Dataset( 0 ); } }); ``` -------------------------------- ### Detect Out-of-Bounds Data Access Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md This example shows how accessing data with a position index that exceeds the dataset's bounds returns null. Use this to validate data access calls. ```javascript dataset.Data(1000) // null if less than 1000 cells ``` -------------------------------- ### Import JSONstat and Initialize Test Suite Source: https://github.com/jsonstat/toolkit/blob/master/test/import.html This snippet demonstrates how to import the JSONstat toolkit and initialize the test suite. It includes a fallback for older browsers that do not support ES modules. Requires a server to work. ```javascript //For old browsers not supporting ES modules window.alert("Sorry, your browser does not support ECMAScript modules!"); import JSONstat from "../import.mjs"; //requires a server to work let html=[] const section=document.querySelector('section'), iterateTests = (tests, J, context) => { let ok = true; tests.forEach(d => { const real = d.real(J, context), passed = real === d.exp, t = passed ? "Passed" : 'Not passed!' ; html.push(`
${d.text}: ${real} (${t})
`); if (!passed) { ok = false; } }); return ok; } html.push(`Running jsonstat-toolkit v. ${JSONstat("version")} test...
`); (async () => { let allTestsPassed = true; for (const def of definitions) { const J = await JSONstat(def.url, typeof def.type!== "undefined" ? def.type : null); let context = {}; if (def.setup) { context = def.setup(J); } const testsPassed = iterateTests(def.tests, J, context); if (!testsPassed) { allTestsPassed = false; } } html.push( allTestsPassed ? `ALL TESTS WERE SUCCESSFULLY PASSED
` : `WARNING: SOME TEST FAILED!
` ); document.getElementById("version").innerHTML += ` (v. ${JSONstat("version")}) `; section.innerHTML=html.join(""); })(); ``` -------------------------------- ### Detect Data Access with Dimension Length Mismatch Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md This example illustrates how providing a data selector with an incorrect number of dimensions results in a null return value. Ensure the selector's dimension count matches the dataset's. ```javascript // Dataset has 3 dimensions but selector has 2 dataset.Data([0, 1]) // null if length !== expected ``` -------------------------------- ### Detect Malformed Dataset with No Dimensions Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md This example shows how to detect a malformed dataset by checking if its length is zero, which implies it has no dimensions. This can occur due to dimension mismatch errors during construction. ```javascript const dataset = json.Dataset(0); if (dataset.length === 0) { console.log("Dataset has no dimensions (malformed)"); } ``` -------------------------------- ### Dataset() Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Gets dataset information from a jsonstat instance. It can be applied to 'bundle', 'collection', or 'dataset' instances. It returns a jsonstat instance for the specified dataset or an array of instances if no dataset ID is provided. ```APIDOC ## Dataset() ### Description Gets dataset information from a jsonstat ("bundle", "collection", "dataset") instance. ### Method N/A (Method of a JSONstat object) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters #### dsid - **dsid** (integer or string) - Required - It can be a positive integer (access by index in the datasets [id](#id) array) or a string (access by ID). ### Return Value When a valid **dsid** is specified, it returns a *jsonstat* instance. If **dsid** is not valid, a *null* is returned. If **dsid** is not specified, it will return an array of *jsonstat* instances: one for each dataset. ### Request Example ```js JSONstat( "https://json-stat.org/samples/oecd-canada.json" ).then(function(j) { if( j.class==="bundle" ){ var ds1=j.Dataset( 0 ); } }); ``` ### Response #### Success Response (200) - **jsonstat instance** or **array of jsonstat instances** or **null** #### Response Example ```json // Example for a single dataset instance { "id": "oecd-canada", "label": "OECD Canada", "status": "ok", "updated": "2016-09-01", "source": "OECD", "role": "dataset", "note": [], "href": "https://json-stat.org/samples/oecd-canada.json", "link": [], "extension": [], "class": "dataset", "length": 3, "n": 1, "size": 1, "value": null, "updated": "2016-09-01", "source": "OECD", "role": "dataset", "note": [], "href": "https://json-stat.org/samples/oecd-canada.json", "link": [], "extension": [], "dimension": [ { "id": "id", "label": "id", "role": "id", "note": [], "href": null, "link": [], "extension": [], "class": "dimension", "length": 1, "n": 1, "size": 1, "value": null, "category": { "index": { "0": 0 }, "label": { "0": "Canada" }, "unit": [], "note": [], "href": null, "link": [], "extension": [], "class": "category", "length": 1, "n": 1, "size": 1, "value": null } } ] } ``` ``` -------------------------------- ### Dice Method Filter Formats Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/api-reference.md Examples illustrating different formats for the filters parameter in the Dice method, including object and array formats for keeping or dropping categories. ```javascript // Object format (recommended) Dice({ area: ["AT", "CA"], year: ["2010", "2011"] }) ``` ```javascript // Array format Dice([["area", ["AT", "CA"]], ["year", ["2010", "2011"]]]) ``` ```javascript // Keep categories (default) Dice({ area: ["AT", "CA"] }) // Keep only AT and CA ``` ```javascript // Drop categories (drop: true) Dice({ area: ["AT", "CA"] }, { drop: true }) // Remove AT and CA, keep others ``` -------------------------------- ### Package.json Configuration for jsonstat-toolkit Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Defines the entry points for different module systems in the package.json file. ```json { "name": "jsonstat-toolkit", "version": "2.2.2", "description": "JSON-stat JavaScript Toolkit: a library to deal with JSON-stat responses.", "main": "main.cjs", "module": "module.mjs", "browser": "import.mjs", "unpkg": "iife.js", "jsdelivr": "iife.js" } ``` -------------------------------- ### Clone and Slice Dataset Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Demonstrates how to clone a dataset before using the Slice method, as Slice modifies the original dataset. Compare the original, subset, and modified dataset. ```javascript JSONstat("https://json-stat.org/samples/galicia.json").then(function(j){ var original=JSON.parse( JSON.stringify( j ) ), subset=j.Slice( { "birth": "T", "age": "T", "time": "2011" } ) //j will be modified ; //Compare original, subset and j }); ``` -------------------------------- ### Build jsonstat-toolkit Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Execute the build command to bundle and minify the library using Rollup. ```bash npm run build ``` -------------------------------- ### JSONstat Constructor with URL and Fetch Options Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Initialize the JSONstat toolkit with a URL and custom fetch options for the HTTP request. ```javascript JSONstat(url, { method: "GET", headers: { ... } }) ``` -------------------------------- ### Get JSONstat Object Class Name as String Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/api-reference.md Use the toString() method to get the class name of a JSONstat object as a string. This provides a simple way to identify the object type. ```javascript const obj = JSONstat(data); obj.toString(); // "dataset" or "collection" or "bundle" ``` -------------------------------- ### Get Dimension Category Labels by Index Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieves an array of category labels for a specified dimension using its index. The 'instance' parameter is set to false to get labels instead of a JSONstat instance. ```js JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { //Array of dimension "area" category labels var arealabels=j.Dimension( "area", false ); //Same as: j.Dimension( "area" ).Category().map( function( e ){ return e.label; } ) }); ``` -------------------------------- ### Create JSONstat Instance from URL (Promise) Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Fetches data from a URL and creates a jsonstat instance. The constructor returns a promise that resolves to the instance. Check the length property for validity. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { if( j.length ){ ... }else{ window.alert( "Wrong response!" ); } }); ``` -------------------------------- ### JSONstat Constructor with URL Input Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Initialize the JSONstat toolkit by providing a URL to fetch JSON-stat data. ```javascript JSONstat("https://json-stat.org/samples/data.json") ``` -------------------------------- ### Get Dataset Values Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Access the values of a dataset. This property is an array. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { if( j.value ){ //23rd value var value23=j.value[22]; } }); ``` -------------------------------- ### Import jsonstat-toolkit as CommonJS (Node.js) Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Import the library using require for CommonJS environments like Node.js. ```javascript const JSONstat = require('jsonstat-toolkit'); const data = JSONstat(jsonObject); ``` -------------------------------- ### Item() Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Gets item information from a jsonstat instance with class "collection". ```APIDOC ## Item( [itemid] ) ### Description Gets item information from a jsonstat instance with class "collection". ### Parameters #### Path Parameters - **itemid** (integer or object) - Optional - The identifier for the item. ### Public Properties - **class** - The class of the item. - **href** - The hyperlink to the item. - **label** - The label of the item. - **extension** - Any extension properties of the item. ### Response #### Success Response (200) - **object** or **array** - Information about the item. ``` -------------------------------- ### JSONstat Constructor with URL, Fetch Options, and TypedArray Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Initialize the JSONstat toolkit with a URL, fetch options, and a TypedArray constructor for numeric values. ```javascript // Or with fetch options JSONstat(url, { method: "GET" }, Float32Array); ``` -------------------------------- ### Include jsonstat-toolkit via CDN (IIFE) Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Load the library in a browser using a script tag from a CDN for IIFE/UMD compatibility. ```html ``` -------------------------------- ### Get Datum Status Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieve the status of an individual data point. This property is a string or null. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { //Status of the 23rd value var status23=j.Data( 22 ).status; }); ``` -------------------------------- ### Create JSONstat Instance from URL with POST Options Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Fetches data from a URL using POST request options, including a query body. The promise resolves to a jsonstat instance. ```javascript var url="https://pxnet2.stat.fi/PXWeb/api/v1/en/StatFin/tym/tyti/vv/statfin_tyti_pxt_11pl.px", query={ "query": [ { "code": "Sukupuoli", "selection": { "filter": "item", "values": [ "SSS" ] } } ], "response": { "format": "json-stat2" } }, options={ method: "POST", redirect: "follow", body: JSON.stringify(query) } ; JSONstat(url, options).then(function( j ) { var label=j.label; }); ``` -------------------------------- ### Get Dataset Status Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Access the status of values within a dataset. This property is an array or null. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { if( j.status ){ //Status of the 23rd value var status23=j.status[22]; } }); ``` -------------------------------- ### Transform() Options Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Configure the output format, column naming, content display, and metadata inclusion for the Transform() method. ```javascript dataset.Transform(options) ``` -------------------------------- ### Get Datum Value Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieve the value of an individual data point. This property is usually a number, but can be a string or null. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { //23rd value var value23=j.Data( 22 ).value; //Same as j.Data( 22, false ) }); ``` -------------------------------- ### Get Dataset Update Date Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieve the update date of the dataset. The date is a string in ISO 8601 format. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { if( j.updated ){ var upd=new Date( j.updated ), timelapse=Date.now()-upd, days=Math.floor( timelapse / ( 1000*60*60*24 ) ) ; window.alert( "This dataset was updated " + String( days ) + " days ago." ); } }); ``` -------------------------------- ### Aggregation Pattern with Unflatten Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/usage-patterns.md Demonstrates an aggregation pattern using Unflatten by first grouping data points by a dimension (e.g., country) and then performing calculations on the grouped values. ```javascript const byCountry = {}; dataset.Unflatten((coordinates, datapoint) => { const country = coordinates.geo; if (!byCountry[country]) { byCountry[country] = []; } byCountry[country].push(datapoint.value); }); // Now aggregate for (const [country, values] of Object.entries(byCountry)) { const avg = values.reduce((a, b) => a + b, 0) / values.length; console.log(`${country}: ${avg}`); } ``` -------------------------------- ### Browser Global Import Path Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Include the JSONstat toolkit via a script tag for use as a browser global (IIFE). ```html ``` -------------------------------- ### arrobj Data Format with Meta Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md When 'meta' is true, returns an object containing metadata and the data array. The metadata provides context about the dataset. ```json { "meta": { "type": "arrobj", "label": "Population by sex and age group. Canada. 2012", "source": "Statistics Canada, CANSIM, table 051-0001", "updated": "2012-09-27", "id": ["country", "year", "age", "concept", "sex"], "status": false, "by": "sex", "drop": ["year", "country"], "prefix": "", "comma": false, "dimensions": { "sex": { "label": "sex", "role": "classification", "categories": { "id": [ "T", "M", "F"], "label": [ "total", "male", "female" ] } }, "age": { ... }, "concept": { ... }, "country": { ... }, "year": { ... } } }, "data": [ ... ] } ``` -------------------------------- ### Retrieving Item URLs Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Get the URL of a specific item within a collection. This is useful for linking to individual data resources. ```javascript JSONstat( "https://json-stat.org/samples/collection.json" ).then(function(j) { //Get the URL of the first item in the collection var href1=j.Item( 0 ).href; }); ``` -------------------------------- ### Get Item Label by Index Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieves the label of the first item in a JSONstat collection by its index. Assumes the collection has been fetched. ```js JSONstat( "https://json-stat.org/samples/collection.json" ).then(function(j) { //Get the label of the first item in the collection var label1=j.Item( 0 ).label; }); ``` -------------------------------- ### Get String Representation Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/module-structure.md Obtain a string representation of the JSONstat object. This method typically returns the value of the 'class' property. ```javascript toString() ``` -------------------------------- ### Get Category Label Source: https://github.com/jsonstat/toolkit/blob/master/README.md Extract the label for a specific category within a dimension. This is useful for understanding the values represented by categories. ```javascript JSONstat( j ).Dataset( 0 ).Dimension( "time" ).Category( 0 ).label ``` -------------------------------- ### Include JSONstat as a Browser Global Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/module-structure.md Include the JSONstat library in a browser environment by referencing the script tag. Access the library via the window.JSONstat object. ```html ``` -------------------------------- ### Get Unit Information for Metric Category Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Access unit information for a category dimension with a 'metric' role. This property is an object or null. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { //First category in the first dimension with a "metric" role var metric1=j.Dimension( { role : "metric" } )[0].Category( 0 ); if( metric1.unit && metric1.unit.hasOwnProperty( "decimals" ) ){ //Decimals of the first category in the first dimension with a "metric" role var dec=metric1.unit.decimals; } }); ``` -------------------------------- ### Retrieving Category Labels Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Get the human-readable label for a specific category within a dimension. This is useful for displaying data in a user-friendly format. ```javascript JSONstat( "https://json-stat.org/samples/oecd.json" ).then(function(j) { //Label for "AU" area (Australia) var label=j.Dataset( "oecd" ).Dimension( "area" ).Category( "AU" ).label; }); ``` -------------------------------- ### Checking for Null Dataset Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md Demonstrates how to safely access a Dataset object by first checking if the returned value is null. This prevents errors when the dataset cannot be found. ```javascript const dataset = json.Dataset(0); if (dataset === null) { console.log("Dataset not found"); return; } ``` -------------------------------- ### Get Dataset by Index from Collection Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Retrieves a dataset by its index from a JSONstat collection instance. This is applicable when the collection contains embedded datasets. ```js JSONstat( "https://json-stat.org/samples/oecd-canada-col.json" ).then(function(j) { if( j.class==="collection" ){ var ds1=j.Dataset( 0 ); } }); ``` -------------------------------- ### JSONstat() - Reading Source: https://github.com/jsonstat/toolkit/blob/master/docs/API.md Initializes the JSON-stat Toolkit to read JSON-stat data. This is the primary entry point for interacting with the toolkit's data reading capabilities. ```APIDOC ## JSONstat() ### Description Initializes the JSON-stat Toolkit to read JSON-stat data. This is the primary entry point for interacting with the toolkit's data reading capabilities. ### Method (Not specified, likely a constructor or initialization function) ### Parameters (Not specified in the source text) ### Request Example (Not specified in the source text) ### Response (Not specified in the source text) ``` -------------------------------- ### Retrieve JSONstat Toolkit Version Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/configuration.md Get the current version of the JSONstat Toolkit programmatically. This is useful for checking compatibility or logging purposes. ```javascript const version = JSONstat("version"); console.log(version); // "2.2.2" ``` -------------------------------- ### Handle Collection with No Items Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/errors.md Manages collections that exist but lack a 'link.item' property, resulting in null or empty arrays for items and datasets. ```javascript if(this.link!==null && o.link.item){ const item=o.link.item; this.length=( Array.isArray(item) ) ? item.length : 0; if(this.length){ this.id = item.map(i => i.href); } } ``` -------------------------------- ### JSONstat(input, init, typedArray) Source: https://github.com/jsonstat/toolkit/blob/master/_autodocs/module-structure.md Main exported function that acts as the public API entry point. It handles direct JSON-stat object parsing, URL fetching, version retrieval, and parameter normalization. ```APIDOC ## JSONstat(input, init, typedArray) ### Description Main exported function. Delegates to jsonstat constructor with proper parameter handling. Handles synchronous object creation, asynchronous URL fetching, and version string retrieval. ### Parameters * **input**: object | string - Can be an object in JSON-stat format, a URL string to fetch, or the string "version" to get the package version. * **init**: object | function (optional) - Fetch options if input is a URL (defaults to { method: "GET" }), or a TypedArray constructor function. * **typedArray**: function (optional) - A TypedArray constructor (e.g., Int8Array, Float32Array). ### Returns * object - A jsonstat instance if the input is an object. * Promise