Search code examples
arraysjsonnode.jsibm-cloud

How to request a JSON API


I am using IBM Bluemix to make a web service for a school project.

My project needs to request a JSON from an API, so I can use the data it provides.

I am not really sure of how to access data contained between [ ] in the JSON. I know this is an array but I don't know how to extract data form it. This is in the end of my .js code, in the http.get method.

My JSON is:

{
    "dataset": {
        "id": 24226,
        "dataset_code": "432",
        "database_code": "BCB",
        "name": "Interest rate - Selic target",
        "description": "Interest rate - Selic target\nUnits: % p.y.",
        "refreshed_at": "2015-11-27T00:33:34.774Z",
        "newest_available_date": "2016-01-20",
        "oldest_available_date": "1999-03-05",
        "column_names": ["Date", "Value"],
        "frequency": "daily",
        "type": "Time Series",
        "premium": false,
        "limit": null,
        "transform": null,
        "column_index": null,
        "start_date": "1999-03-05",
        "end_date": "2016-01-20",
        "data": [
            ["2016-01-20", 14.25],
            ["2016-01-19", 14.25],
            ["2016-01 -18", 14.25]
        ],
        "collapse": null,
        "order": "desc",
        "database_id": 35
    }
}

I just want to get a few dates and their respective values to use in my code, like [2016-01-20]:14.25, for instance.

Here is my .js file :

// Hello.
//
// This is JSHint, a tool that helps to detect errors and potential
// problems in your JavaScript code.
//
// To start, simply enter some JavaScript anywhere on this page. Your
// report will appear on the right side.
//
// Additionally, you can toggle specific options in the Configure
// menu.

function main() {
  return 'Hello, World!';
}

main();/*eslint-env node*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// HTTP request - duas alternativas
var http = require('http');
var request = require('request');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

//chama o express, que abre o servidor
var express = require('express');

// create a new express server 
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
    // print a message when the server starts listening
    console.log("server starting on " + appEnv.url);
});


app.get('/home1', function (req,res) {
    http.get('http://developers.agenciaideias.com.br/cotacoes/json', function (res2) {
        var body = '';
        res2.on('data', function (chunk) {
            body += chunk;
        });
        res2.on('end', function () {
            var json = JSON.parse(body);
            var CotacaoDolar = json["dolar"]["cotacao"];
            var VariacaoDolar = json["dolar"]["variacao"];
            var CotacaoEuro = json["euro"]["cotacao"];
            var VariacaoEuro = json["euro"]["variacao"];
            var Atualizacao = json["atualizacao"];

            obj=req.query; 

            DolarUsuario=obj['dolar'];
            RealUsuario=Number(obj['dolar'])*CotacaoDolar;

            EuroUsuario=obj['euro'];
            RealUsuario2=Number(obj['euro'])*CotacaoEuro;

            Oi=1*VariacaoDolar;
            Oi2=1*VariacaoEuro;

            if (VariacaoDolar<0) {
            recomend= "Recomenda-se, portanto, comprar dólares.";
            }

            else if (VariacaoDolar=0){
                recomend="";
            }

            else {
                recomend="Recomenda-se, portanto, vender dólares.";
                  }

            if (VariacaoEuro<0) {
            recomend2= "Recomenda-se, portanto, comprar euros.";
            }

            else if (VariacaoEuro=0){
                recomend2="";
            }
            else {
                recomend2="Recomenda-se,portanto, vender euros.";
                  }   

            res.render('cotacao_response.jade', {
                         'CotacaoDolar':CotacaoDolar,
                        'VariacaoDolar':VariacaoDolar,
                        'Atualizacao':Atualizacao,
                        'RealUsuario':RealUsuario,
                        'DolarUsuario':DolarUsuario,
                        'CotacaoEuro':CotacaoEuro,
                        'VariacaoEuro':VariacaoEuro,
                        'RealUsuario2':RealUsuario2,
                        'recomend':recomend,
                        'recomend2':recomend2,
                        'Oi':Oi,
                        'Oi2':Oi2
            });

            app.get('/home2', function (req,res) {
    http.get('https://www.quandl.com/api/v3/datasets/BCB/432.json', function (res3) {
        var body = '';
        res3.on('data', function (chunk) {
            body += chunk;
        });
        res2.on('end', function () {
            var json = JSON.parse(body);
            var ultimo= json[data]["0"]["1"];
            console.log("a meta é"+ultimo)
        )};
    )};
            )};
        )};
    )};
)};

Solution

  • To access data in the above data structure, specifically in the the array `data. You can use the syntax below.

    The following assumes your data is stored in a variable called json.

    json.dataset.data[0]
    

    You can access the first element of the array with the [0], this means access the first element in the array. Array indexing starts at 0.

    If you wanted to go deeper the above code will return the following.

    [ '2016-01-20', 14.25 ]
    

    If you wanted to access the date you could use the following.

    json.dataset.data[0][0]
    

    It would return the following.

    2016-01-20
    

    If you wanted to access the the other value you could use the following.

    json.dataset.data[0][1]
    

    It would return the following.

    14.25