The INEGI Indicators API allows consulting the data and metadata of the available nationwide indicators, by state and municipality. You can use the API to create applications that display information directly from INEGI databases at the exact moment it is updated.
Welcome to the documentation for developers of the INEGI Indicators API. INEGI joins the open access data initiative with the aim of expanding the availability of information for users.
This documentation is intended for developers familiar with JavaScript programming and knowledge of object-oriented programming.
The first step to obtain information from the API is to select the indicator and identify its key. This can be done by consulting the "Query Builder".
LanguageThe information is available in Spanish [es] and English [en].
Geographic areaIt can be national [00], by federal entity [99] or by municipality [999], depending on each indicator.
Most recent data or historical seriesOnly the most recent data [true] or the complete historical series [false] can be consulted.
Data sourceIt corresponds to the source of dissemination [BISE] or [BIE] from which the consulted data will be obtained.
VersionThe edition [2.0] of the data provision service will be identified with it.
TokenTo use the API it is necessary to send a valid token, which you can obtain when registering here.
FormatThe information is offered in 3 types of formats: JSON [json], JSONP [jsonp] or XML [xml].
Structure name.
EmailInstitute Email.
Unique identifier of the indicator.
FREQInformation on update frequency.
TOPICTopic ID.
UNITUnit of measure.
UNIT_MULTIndicator multiplier unit.
NOTENotes related to the indicator.
SOURCEIndicator source or program.
LASTUPDATEIndicator update date.
STATUSIndicator status.
OBSERVATIONS
TIME_PERIODObservation period.
OBS_VALUEValue of observation.
OBS_EXCEPTIONException when a value does not exist.
OBS_STATUSStatus of observation.
OBS_SOURCESource or program related to the observation.
OBS_NOTENotes related to observation.
COBER_GEOGeographic area ID.
Identifies [CL_UNIT] to the list of data that complement the indicator. This can be done by consulting the "Query Builder".
IdCatalogoIdentification key to get a record [1] or all [null] records in the catalog.
LanguageThe information is available in Spanish [es] and English [en].
Data sourceIt corresponds to the source of dissemination [BISE] or [BIE] from which the consulted data will be obtained.
VersionThe edition [2.0] of the data provision service will be identified with it.
TokenTo use the API it is necessary to send a valid token, which you can obtain when registering here.
FormatThe information is offered in 3 types of formats: JSON [json], JSONP [jsonp] or XML [xml].
It is the identifier of the selected method["INDICATOR"].
AgencyIDIt is the identification of the agency that provides the data ["INEGI"].
VersionIt is the Version of the method used to obtain the data [2.0].
LanguageIt is the key of the language in which the data is provided ["es"].
CODE It is the arrangement of the data obtained, each element consists of the following attributes.
Value: It is an identifier of the data.
Description: It is the description of the data.
If you are Web Service's user, now you can obtain the information by using the following methods of the Indicators Bank API:
Indicators method - for consulting indicators.
Metadata Catalog method. - for consulting catalogs.
PC-Axis is a specialized statistical program that is a standard in terms of data dissemination.
PC-Axis is a free program developed by Statistics Sweden for querying multidimensional statistical tables. This program is used by a significant number of statistical offices and its features include the following: Table customization, which allows the user to decide which variables and values are involved and in what order. Typical calculations in a statistical table without writing formulas. Preparation of statistical graphs. Export and copy data to other applications. PC-Axis is used to query on your desktop the data tables that INEGI broadcasts in PX format through its e-Base repository. The PC-Axis program is not required to query publications on the Internet, however, PC-Axis is required to work with e-Base tables that are downloaded in this format.
Existing Pc-Axis tools have been developed by organizations actively involved in the standard and are generally distributed under open source license. To get started with the standard in a basic way, we recommend that you use the following:
PC-Axis 2008PC-Axis 2008 is a program for Windows 95/98/NT/2000/XP and for Windows Vista. The installation procedure will leave PC-Axis files (extension *.px) associated with this program, so that your Internet browser will recognize them as such and directly launch the PC-Axis program. If this does not happen, review your browser settings for associated applications. In order to use the program, you must have administrator permission on the computer. Download PC-Axis 2008
Px-mapFree software developed by the Norwegian Statistics Institute that allows you to present statistics using thematic maps. px-map is developed to work fully integrated with pc-axis. compatible with windows 95/98/me/nt/2000/xp, it is necessary to install pc-axis 2005 previously. Note: The installation process is in English. simply accept the default options. Once the process is done, it is necessary to install the map templates of the Basque country (available on this same page) if the pc-axis files with which you will work allow the use of maps. Download Px-map
Px-map helpOnce px-map is installed it is possible to install the help and menus in Basque or Spanish for you to work in the language you want. Note: The installation process is in Spanish. simply accept the default options.. Download Px-map
The first step to obtain information from the API is to select the indicator and identify its key. This can be done by consulting the "Query Builder".
LanguageThe information is available in Spanish [es] and English [en].
Geographic areaIt can be national [00], by federal entity [99] or by municipality [999], depending on each indicator.
Most recent data or historical seriesOnly the most recent data [true] or the complete historical series [false] can be consulted.
Data sourceIt corresponds to the source of dissemination [BISE] or [BIE] from which the consulted data will be obtained.
TokenTo use the API it is necessary to send a valid token, which you can obtain when registering here.
FormatIt is required to use the Pc-Axis typer [pcAxis].
Type: text
Length: 20 characters
Multiline: No
CHARSET=”ANSI”; indicates that the texts in the file are written in Windows format. If the keyword is missing it means that the texts in the file are in DOS format. They will be translated by PC-Axis to Windows. This keyword must appear in the beginning of the file before any texts that can include characters outside A-Z, 0-9.
Type: text
Length: 20 characters
Multiline: No
Version number for PC-Axis (new text length 2008). Is read and saved but otherwise not used.
Type: text
Length: 20 characters
Multiline: No
Is used when creating XML format to get correct characters. Default iso-8859-1. Max 20 chars.
Type: text
Length: 2 characters per language
Multiline: No
The language used in the PC-Axis file (2 chars), sv for Swedish, en for English etc. Compare language codes for text files. If the keyword is used, the words for “and” and “by” are read from the text file of that language. Otherwise these words are read from the text file of the language in which the program is running.
Type: text
Length: 256 characters
Multiline: Yes
Date when file was created. Written in format CCYYMMDD hh:mm, e.g. ”19960612 14:20”. Is shown together with footnotes.
Type: integer [0, 15]
Length: Lines of 256 characters
Multiline: No
The number of decimals in the table cells. 0 - 15. (0-6 if SHOWDECIMALS is not included). Indicates how many decimals will be saved in the PC-Axis file. Written without quotation marks. Compare SHOWDECIMALS.
Type: integer
Length: N/A
Multiline: No
The number of decimals to be shown in the table, 0-6. Must be the same or smaller than the number stored as indicated by the keyword DECIMALS. If SHOWDECIMALS is not stated in the file the number stated by DECIMALS will be used.
Type: text
Length: 20
Multiline: No
The name of the matrix. Is suggested as file name when the file is fetched. (new length 2008).
Type: text
Length: 20 characters
Multiline: No
Copyright is given as YES or NO. If COPYRIGHT=YES the copyright refers to the organization given in SOURCE. Is shown together with footnotes.
Type: text
Length: 20 characters
Multiline: No
Subject area code. It is used to create files with tables available in PC-Axis. The text must not exceed 20 characters (new length 2008).
Type: text
Length: 256 characters
Multiline: No
The name of the subject area in plain text, as shown in the menu "Select subject area". The text must not exceed 256 characters (new length in 2008).
Type: text
Length: Lines of 256 characters
Multiline: Yes
The title of the table, reflecting its contents and variables. Is not needed if the file contains DESCRIPTION, in that case the text belonging to description is used. How the heading of a table will look depends on which variables the user chooses; the heading thus created will then be saved as TITLE. (Compare also DESCRIPTIONDEFAULT)
If the file contains DESCRIPTION the text for this key word will be used.
Type: text
Length: 256 characters
Multiline: No
Information about the contents, which makes up the first part of a title created when retrieving tables from PC-Axis. The text must not exceed 256 characters (before 2002 only 100 chars).
Type: text
Length: 256 characters per valuer
Multiline: Yes
At least one of the keywords STUB or HEADING must be included. Usually both are included, as you choose one or several variables for the stub and the heading, respectively. The keywords are followed by a list with the chosen variables. The variables are within quotation marks and separated by commas. If the list with the variables has to be divided up into several lines, this should be done after a comma and not within the variable name.
Type: text
Length: 256 character per value
Multiline: Yes
At least one of the keywords STUB or HEADING must be included. Usually both are included, as you choose one or several variables for the stub and the heading, respectively. The keywords are followed by a list with the chosen variables. The variables are within quotation marks and separated by commas. If the list with the variables has to be divided up into several lines, this should be done after a comma and not within the variable name.
Type: text
Length: 256 characters per value
Multiline: Yes
The keyword VALUES occurs once for each variable in the table, and is followed by the variable name in parentheses, within quotation marks. The values will be in the same order as in the stub and heading, respectively. They are within quotation marks and separated by commas. Each value name must not exceed 256 characters. If the values have to be divided up into several lines, this should be done after a comma and not within the value name. See also the keyword TIMEVAL below.
Type: text
Length: 256 characters
Multiline: No
Unit text, e.g. ton, index. The text must not exceed 256 characters (new length 2008). Compare UNITS for CONTVARIABLE.
When there is a CONTVARIABLE the keyword UNITS takes an index and is repeated for every value for the contents variable. UNITS("value")="tons".
Type: text
Length: 256 characters
Multiline: Yes
A footnote for separate variable values. Should be written with the variable name and the value names in parentheses.
Type: text
Length: 256 characters
Multiline: Yes
States the organization which is responsible for the statistics. Is shown with the footnote.
Type: text
Length: 20 characters
Multiline: No
This if used to indicate how a stored “.” is to be presented in a table.
Type: integer/text
Length: N/A
Multiline: Yes
The keyword DATA must be placed at the end of the file, followed by all the data cells or if KEYS are used the variable values and all data cells that differ from 0.
The main statistical standards for data and metadata exchange are XML-based: they are generally complicated and detailed, so JSON-Stat comes to change this paradigm.
JSON-stat is a lightweight and simple JSON broadcast format, more suitable for viewing data, mobile applications or open data initiatives, which has been designed for all types of broadcasters.
JSON-stat also proposes an HTML microdata scheme to enrich HTML tables and put the JSON-stat vocabulary in the browser.
JSON-stat comes with libraries and sample code for various programming languages: JavaScript, R, Java, Python, Julia, PHP or even the command line.
See more...
As part of the tools you can use the visualizer to deploy the datso and metadata online. See more...
In addition there is an online application that allows you to verify the correct construction of the Json-Stat file. See more...
The first step to obtain information from the API is to select the indicator and identify its key. This can be done by consulting the "Query Builder".
LanguageThe information is available in Spanish [es] and English [en].
Geographic areaIt can be national [00], by federal entity [99] or by municipality [999], depending on each indicator.
Most recent data or historical seriesOnly the most recent data [true] or the complete historical series [false] can be consulted.
Data sourceIt corresponds to the source of dissemination [BISE] or [BIE] from which the consulted data will be obtained.
TokenTo use the API it is necessary to send a valid token, which you can obtain when registering here.
FormatUsing the json-stat [jsonStat] typeifier is required..
Declares the JSON-stat version of the response. The goal of this property is to help clients analyze that particular response. Because future releases might add optional properties, the same response can be valid in multiple versions: any of those versions are accepted as a version value.
Before version 2.0
The version was introduced in version 2.0. That's why this property cannot accept values less than 2.0.
JSON-stat supports several kinds of responses. The possible values of the class are: dataset, dimension, and collection. Dataset responses include a single dataset. They are declared using the value of the dataset class.
HrefSpecifies a URL.
Vendors can use this property to prevent the sending of information that is shared between different requests (for example, dimensions)..
Used to assign very short descriptive text (a line) to IDs at different levels of the response tree. It's language-dependent.
When it is a root property or a child of dimension ID or a unit category ID, it is a string.
Contains data sorted by dataset dimensions. It usually takes the form of an array where missing values are expressed as null.
StatusContains observation-level metadata. When you take an array shape of the same value size, it assigns a state to each data per position.
IdIt is used to describe a particular dimension. The name of this object must be one of the strings in the id array. There must be a single dimension ID object for each dimension in the id array.
SizeContains the number (integer) of categories (possible values) of each dimension in the dataset. It has the same number of elements and in the same order as in id.
DimensionJSON-stat follows a cube model: values are organized into cells, and a cell is the intersection of multiple dimensions. The dimension property contains information about the dimensions of the dataset.
CategoryUsed to describe the possible values of a dimension.
UnitUsed to describe the possible values of a dimension.
See more...Obtain data from the historical series of the Total Population indicator, in the United Mexican States, in Spanish language, in JSON format.
Inquiry:
Result:
URL Query
Result:
<!DOCTYPE html > <html xmlns="http://www.w3.org/1999/xhtml"> <head > <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title ></title > <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script > <script type="text/javascript" src="js/llamarAPI.js"></script > <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script ></head > <body > <div id="chart" style="width: 100%; min-height: 550px;"></div > <div id="NoteChart"></div > <div id="FuenteChart"></div > </body > </html >
google.charts.load('current',{'packages': ['corechart', 'bar']}); google.charts.setOnLoadCallback(drawChart); var arrayChartData=[]; //Ingtention of the indicator data structure with parameters //Indicator: 1002000002 //Language: es //Key entity: 01 //Resentful data: false //Data source: BISE //Version: 2.0 var urlDataStructure="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/INDICATOR/1002000001/en/00/false/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataStructure, function (dataStructure){ var Observations=dataStructure.Series[0].OBSERVATIONS; for (var i=0; i <=Observations.length - 1; i++) {arrayChartData[i]=[Observations[i].TIME_PERIOD, parseInt(Observations[i].OBS_VALUE), '#E16c32'];} }); //Indicator metadata undergoing //Catalog: CL_INDICATOR //Indicator: 1002000002 //Language: es //Data source: BISE //Version: 2.0 var dataCL_INDICATOR; var urlDataCL_INDICATOR="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_INDICATOR/1002000001/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_INDICATOR, function (dataCatalog){ dataCL_INDICATOR={Descripcion: dataCatalog.CODE[0].Description, AgencyID: dataCatalog.agencyID,}}); //Obetencion de la unidadde medida del indicador con los parametros //Catalog: CL_UNIT //Key: 96 //Language: es //Data source: BISE //Version: 2.0 var dataCL_UNIT; var urlDataCL_UNIT="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_UNIT/96/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_UNIT, function (dataCatalog){ dataCL_UNIT={Descripcion: dataCatalog.CODE[0].Description, Value: dataCatalog.CODE[0].value,} }); //Obetenation of the indicator note with the parameters //Catalog: CL_NOTE //Key: 1398 //Language: es //Data source: BISE //Version: 2.0 var dataCL_NOTE; var urlDataCL_NOTE="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_NOTE/1398/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_NOTE, function (dataCatalog){ dataCL_NOTE={Descripcion: dataCatalog.CODE[0].Description, Value: dataCatalog.CODE[0].value,} }); //Obetention of the indicator source with the parameters //Catalog: CL_SOURCE //Key: 2,3,343,487,510 //Language: es //Data source: BISE //Version: 2.0 var dataCL_SOURCE; var urlDataCL_SOURCE="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_SOURCE/2,3,343,487,510/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_SOURCE, function (dataCatalog){ var descripcion=""; var value=""; for (var i=0; dataCatalog.CODE.length >i; i++){ descripcion=descripcion + " " + dataCatalog.CODE[i].Description; value=value + " " + dataCatalog.CODE[i].value; } dataCL_SOURCE={Descripcion: descripcion, Value: value,} }); //Obetenation of the indicator theme with the parameters //Catalog: CL_TOPIC //Key: 2,3,343,487,510 //Language: es //Data source: BISE //Version: 2.0 var dataCL_TOPIC; var urlDataCL_TOPIC="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_TOPIC/2,3,343,487,510/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_SOURCE, function (dataCatalog){var descripcion=""; var value=""; for (var i=0; dataCatalog.CODE.length >i; i++) {descripcion=descripcion + " " + dataCatalog.CODE[i].Description; value=value + " " + dataCatalog.CODE[i].value; } dataCL_SOURCE={Descripcion: descripcion, Value: value,} }); //Failure to frequency or periodicity of the indicator with the parameters //Catalog: CL_FREQ //Key: 2,3,343,487,510 //Language: es //Data source: BISE //Version: 2.0 var dataCL_FREQ; var urlDataCL_FREQ="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_FREQ/7/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_FREQ, function (dataCatalog){ var descripcion=""; var value=""; dataCL_FREQ={Descripcion: dataCatalog.CODE[0].Description, Value: dataCatalog.CODE[0].value,} }); //Obetenation of the entity or municipality of the indicator with the parameters //Catalog: CL_GEO_AREA //Key: 00 //Language: es //Data source: BISE //Version: 2.0 var dataCL_GEO_AREA; var urlDataCL_GEO_AREA="https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/CL_GEO_AREA/00/en/BISE/2.0/[Here's your Token]?type=json"; $.getJSON(urlDataCL_GEO_AREA, function (dataCatalog){ var descripcion=""; var value=""; dataCL_GEO_AREA={Descripcion: dataCatalog.CODE[0].Description, Value: dataCatalog.CODE[0].value,}} ); //It worked to paint the graph function drawChart(){ document.getElementById("NoteChart").innerHTML='<b >Nota </b ><br >' + dataCL_NOTE.Descripcion; document.getElementById("FuenteChart").innerHTML='<b >Fuente </b ><br >' + dataCL_SOURCE.Descripcion; var data=google.visualization.arrayToDataTable([[{role: "domain", Label: "Year", type: "string"}, { Label: "Valor", role: "data", type: "number" }, {role: "style"}]]); data.addRows(arrayChartData); var view=new google.visualization.DataView(data); var options={title:dataCL_INDICATOR.Descripcion + " (Periodicidad:" + dataCL_FREQ.Descripcion +", Geographic area: "+dataCL_GEO_AREA.Descripcion+")", titleTextStyle:{ fontSize: 14, color: 'black', bold: true, italic: false}, chart:{title: 'Company Performance', subtitle: 'Sales, Expenses, and Profit: 2014-2017',}, legend:{position: "none"}, hAxis:{title: 'Years', format: 'yyyy', textStyle:{fontSize: 12, color: 'Black', bold: true, italic: false}, titleTextStyle:{fontSize: 12, color: 'Black', bold: true, italic: false}}, vAxis:{title: dataCL_UNIT.Descripcion, min:1, textStyle:{fontSize: 12, color: 'Black', bold: false, italic: false,}, titleTextStyle:{fontSize: 12, color: 'Black', bold: true, italic: false} }}; var chart=new google.visualization.ColumnChart(document.getElementById('chart')); chart.draw(view, options);}$(window).resize(function (){drawChart();});
Obtain data from the historical series of the Total Population indicator, in the United Mexican States, in Spanish language, in JSON format and calculate its average.
import requests import json #API call url='https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/INDICATOR/1002000002/en/00000/false/BISE/2.0/[Here's your Token]?type=json' response= requests.get(url) if response.status_code==200: content= json.loads(response.content) Series=content['Series'][0]['OBSERVATIONS'] #Getting the list of observations Observaciones=[] for obs in Series: Observaciones.append(float(obs['OBS_VALUE'])); #Generating the average of the list of observations sum=0.0 for i in range(0,len(Observaciones)): sum=sum+Observaciones[i]; resultado=sum/len(Observaciones); print(resultado)
Obtain data from the historical series of the Total Population indicator, in the United Mexican States, in Spanish language, in JSON format and calculate its average.
library(httr) library(jsonlite) library(rjson) #API call url <-"https://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/INDICATOR/1002000001/en/00000/false/BISE/2.0/[Here's your Token]?type=json" respuesta<-GET(url) datosGenerales<-content(respuesta,"text") flujoDatos<-paste(datosGenerales,collapse = " ") #Getting the list of observations flujoDatos<-fromJSON(flujoDatos) flujoDatos<-flujoDatos $Series flujoDatos<-flujoDatos[[1]] $OBSERVATIONS #Generating the average of the list of observations datos<-0; for (i in 1:length(flujoDatos)){ datos[i]<-flujoDatos[[i]] $OBS_VALUE } datos<-as.numeric(datos) print(mean(datos))
Obtain data from the historical series of the Total Population indicator, in the United Mexican States, in Spanish language, in PC-Axis format.
URL Query
Result:
<!DOCTYPE html > <html> <head> <link href="c3/c3.css" rel="stylesheet" type="text/css"> </head> <body> <div id="chart"></div> <div id="chartPcAxis"></div> <script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script> <script src="c3/c3.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="JSPc-Axis/px.js"></script> <script src="JSPc-Axis/underscore.js"></script>; </body > </html >
window.onload = function() { getPcAxis(); } function buildPcAxis() { return new Promise(function(resolve, reject) { var urlApiPcAxis = "http://www.inegi.org.mx/app/api/indicadores/desarrolladores/jsonxml/PCAXIS/1002000001/en/00/false/BISE/[Here's your Token]?type=pcAxis"; $.ajax({ type: "GET", url: urlApiPcAxis, //async: false, headers: { Accept: "text/px" }, success: function(data, status, jqXHR) { resolve(data); }, error: function(jqXHR, status) { reject(jqXHR); } }); }) } function buildChart(px) { const _column = [px.metadata["VALUES "].Indicadores]; for (var i = 0; i < px.data.length; i++) { _column.push(parseFloat(px.data[i])) } const _X = ["x"]; for (var i = 0; i < px.metadata["VALUES "].Tiempo.length; i++) { _X.push(px.metadata["VALUES "].Tiempo[i]); } var chartPcAxis = c3.generate({ bindto: '#chartPcAxis', data: { x: 'x', colors: { '(1002000001) Población total': '#FF9124' }, columns: [ _X, _column ], type: 'bar', onclick: function(d, element) { //console.log("onclick", d, element); }, onmouseover: function(d) { //console.log("onmouseover", d); }, onmouseout: function(d) { //console.log("onmouseout", d); } }, axis: { x: { type: 'categorized', label: 'X Label' }, y: { label: { text: px.metadata.UNITS.TABLE, position: 'outer-middle' } } }, bar: { width: { ratio: 0.3, //max: 30 }, } }); } function getPcAxis() { buildPcAxis().then(r => { buildChart(new Px(r)); }).catch(() => { console.log('Algo salió mal'); }); }
Obtain data from the historical series of the Total Population indicator, in the United Mexican States, in Spanish language, in Json-Stat format.
Inquiry:
Result:
<!DOCTYPE html > <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script> <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"> </script> </head> <body> <div id="barCharJsonStat"></div> </body> </html>
/* JSON-stat JS Sample Code http://json-stat.org/tools/js.txt Author: Xavier Badosa (http://xavierbadosa.com) Date: 2015-12-22 Version: 1.0.1 Copyright 2015 Xavier Badosa License: Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 */ var query = { "CL_GEO_AREA": "", "INDICADOR": "", "TIME_PERIOD": "" }; var arrayCharMorisArray = []; window.onload = function() { inicio(); } function inicio() { getJsonStat().then(r => { console.log(r) main(r); }).catch(() => { console.log('Algo salió mal'); }); } function main(obj) { //Validate jsonstat var jsonstat = JSONstat(obj); if (!jsonstat) { return; } var timeline = Object.keys(obj.dimension.TIME_PERIOD.category.index); console.log(timeline); for (var i = 0; i <= timeline.length - 1; i++) { query.CL_GEO_AREA = "0700"; query.INDICADOR = "1002000002"; query.TIME_PERIOD = timeline[i]; //Parse: Get value from jsonstat and query var value = getValue(jsonstat, query); //Write: Display query and result // show(query, value); addCharMorisArray(query, value); } arrayCharMorisArray; buidChatBarMoris(arrayCharMorisArray) } // Obtencion de los dastos en formato JsonStat function getJsonStat() { return new Promise(function(resolve, reject) { var urlApiPcAxis = "app/api/indicadores/desarrolladores/jsonxml/JSONSTAT/1002000002/en/0700/false/BISE/96fbd1bf-21e6-28e3-6e64-2b15999d2c89?type=jsonStat"; $.ajax({ type: "GET", url: urlApiPcAxis, //async: false, /*headers: { Accept: "application/jsonStat" },*/ success: function(data, status, jqXHR) { resolve(data); }, error: function(jqXHR, status) { reject(jqXHR); } }); }) } //getValue() converts a dimension/category object into a data value in three steps. //Input example: {"concept":"UNR","area":"US","year":"2010"} //Output example: 9.627692959 function getValue(jsonstat, query) { //1. {"concept":"UNR","area":"US","year":"2010"} ==> [0, 33, 7] var indices = getDimIndices(jsonstat, query); //2. [0, 33, 7] ==> 403 var index = getValueIndex(jsonstat, indices); //3. 403 ==> 9.627692959 return jsonstat.value[index]; } //getDimIndices() converts a dimension/category object into an array of dimensions' indices. //Input example: {"concept":"UNR","area":"US","year":"2010"} //Output example: [0, 33, 7] function getDimIndices(jsonstat, query) { var dim = jsonstat.dimension, ids = jsonstat.id || dim.id; //JSON-stat 2.0-ready for (var arr = [], i = 0, len = ids.length; i < len; i++) { arr[i] = getDimIndex(dim, ids[i], query[ids[i]]); } return arr; } //getValueIndex() converts an array of dimensions' indices into a numeric value index. //Input example: [0, 33, 7] //Output example: 403 function getValueIndex(jsonstat, indices) { var size = jsonstat.size || jsonstat.dimension.size; //JSON-stat 2.0-ready for (var i = 0, ndims = size.length, num = 0, mult = 1; i < ndims; i++) { mult *= (i > 0) ? size[ndims - i] : 1; num += mult * indices[ndims - i - 1]; } return num; } //getDimIndex() converts a dimension ID string and a category ID string into the numeric index of that category in that dimension. //Input example: "area", "US" //Output example: 33 function getDimIndex(dim, name, value) { //In single category dimensions, "index" is optional if (!dim[name].category.index) { return 0; } var ndx = dim[name].category.index; if (name.toUpperCase().indexOf("TIME") == 0) { var res = dim[name].category } //"index" can be an object or an array if (Object.prototype.toString.call(ndx) !== "[object Array]") { //Object return ndx[value]; } else { //Array return ndx.indexOf(value); //Polyfill required in old browsers } } //Validate function JSONstat(jsonstat) { if (!jsonstat) { window.alert("Error: no response could be retrieved."); return NULL; } //If no "class", "bundle" response: //use the first dataset available //(assuming single dataset bundle response) //[Of course, it'd be better to add an argument //to the function to pass a dataset ID if //bundle responses must be properly supported.] if (!jsonstat.class) { jsonstat = jsonstat[Object.keys(jsonstat)[0]]; //Polyfill required in old browsers } else { //Verify it's a "dataset" response if (jsonstat.class !== "dataset") { window.alert("Error: response was not a JSON-stat bundle or dataset response."); return NULL; } } //Program requires "value" and "dimension" properties if (!jsonstat.value || !jsonstat.dimension) { window.alert("Error: response is not valid JSON-stat or does not contain required information."); return NULL; } return jsonstat; } //show() displays the query and its result. function show(query, result) { var text = ""; for (var prop in query) { text += prop + "=" + query[prop] + " "; } text += "==> " + result; document.getElementsByTagName("p")[0].innerHTML = text; } function addCharMorisArray(query, result) { //var var text = ""; var dataCharMoris = { "TIME_PERIOD": "", "OBS": 0 } for (var prop in query) { if (prop == "TIME_PERIOD") { dataCharMoris.TIME_PERIOD = query[prop]; } } dataCharMoris.OBS = result == undefined ? 0 : result; arrayCharMorisArray.push(dataCharMoris); } function buidChatBarMoris(arrayCharMorisArray) { var config = { data: arrayCharMorisArray, //data, xkey: 'TIME_PERIOD', barColors: ['#CF6F40'], ykeys: ['OBS'], labels: ['OBS'], fillOpacity: 0.6, hideHover: 'auto', resize: true, }; config.element = 'barCharJsonStat'; Morris.Bar(config); }