Nodejs ler json time series line by line

Asked

Viewed 40 times

0

Access an API, which predicts future values, the API returns me the JSON below:

{ series:
   { '2020-02-13': '62.5000',
     '2020-02-14': '64.5800',
     '2020-02-15': '30.7700',
     '2020-02-16': '60.8700',
     '2020-02-17': '58.5400',
     '2020-02-18': '68.3800',
     '2020-02-19': '83.6900',
     '2020-02-20': '76.1900',
     '2020-02-21': '55.2000',
     '2020-02-22': '75.1700',
     '2020-02-23': '46.4900',
     '2020-02-24': '43.8000',
     '2020-02-25': '88.6500',
     '2020-02-26': '79.1400',
     '2020-02-27': '53.3900',
     '2020-02-28': '64.0600',
     '2020-02-29': '74.4500',
     '2020-03-01': '73.6800',
     '2020-03-02': '77.9100',
     '2020-03-03': '67.8600',
     '2020-03-04': '66.0400',
     '2020-03-05': '38.9500',
     '2020-03-06': '51.4300',
     '2020-03-07': '63.0400',
     '2020-03-08': '58.3300',
     '2020-03-09': '55.4500',
     '2020-03-10': '59.7400',
     '2020-03-11': '63.7700',
     '2020-03-12': '76.7300',
     '2020-03-13': '89.8000',
     '2020-03-14': '69.2300',
     '2020-03-15': '69.7400',
     '2020-03-16': '31.2500',
     '2020-03-17': '59.8100',
     '2020-03-18': '92.8600',
     '2020-03-19': '48.4200' } }

I need to read these values line by line because I will add them in a database, example of what I will do in each line reading:

insert into previsao (dia, valor) VALUES (json.dia, json.valor)

1 answer

1


Hello,

You can convert the data obtained from the API to JSON, thus:

const data = JSON.parse(response);

Right after you get the data and turn it into an object, you can put it into an array, like this:

const entries = Object.entries(data.series);

Which will return the following matrix (only the first 3 vectors):

[
    ["2020-02-13", "62.5000"],
    ["2020-02-14", "64.5800"],
    ["2020-02-15", "30.7700"]
]

So you can access them like this:

for (const entrie of entries) {
    console.log(entrie); // ["2020-02-13", "62.5000"] na primeira execução, e assim vai...

    console.log(entrie[0], entrie[1]); // 2020-02-13 62.5000
}

I hope this helps.

  • When trying to pass the return to json 'const dataJson = JSON.parse(data);', I get the error: Syntaxerror: Unexpected token o in JSON at position 1 at JSON.parse (<Anonymous>) at Request.request.post [as _callback] (F: Development Node direct release releases)

  • Matheus, see if your date is no longer an object, otherwise use the console.log(data) to see what is returning... it has to be in an object format ({ chave: "valor" })

  • Lucas thanks, it was like const Entries = Object.Entries(data.series); for (const entrie of Entries) {.... , it worked

  • Good, Matheus! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.