Answer the question
In order to leave comments, you need to log in
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.
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
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}))
)
);
});
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 questionAsk a Question
731 491 924 answers to any question