Y
Y
Yurii Nekrasov2016-12-03 13:30:54
JavaScript
Yurii Nekrasov, 2016-12-03 13:30:54

How to get JSON from byte array?

The essence of the task: to display the exchange rates of the Central Bank of the Russian Federation
on the front. The answer comes compressed (gzip). I receive an array of bytes, convert it to a string in a loop and send it to the front, also with Cyrillic encoding problems.
4c7abb42989842d8acb8f8c35433ccac.png
That's all I've achieved so far. How do I get the JSON out of this so I can continue working with it on the front using React.js?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aves, 2016-12-03
@driversti

const {get} = require('http');
const {Iconv} = require('iconv');
const {parseString} = require('xml2js');
const {inspect} = require('util');

get('http://www.cbr.ru/scripts/XML_daily.asp', res => {
  const data = [];
  res
    .pipe(new Iconv('cp1251', 'utf8'))
    .on('data', chunk => data.push(chunk))
    .on('end', () =>
      parseString(
        Buffer.concat(data),
        (err, res) => console.log(inspect(res, {depth: null}))
      )
    );
});

R
Rsa97, 2016-12-03
@Rsa97

Why do you need an array of bytes?
For starters, if you want a non-gzip returned to you, pass the 'Accept-Encoding' header correctly in the request, or don't pass it at all.
Then, XML comes to you, its encoding is specified in the first line (Windows-1251). Accordingly, you can convert to any encoding you need.
It remains only to parse the XML and generate JSON in the format you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question