const request = require('request');
const url = 'https://api.darksky.net/{secret_key}/37.8267,-122.4233';
request({ url }, (error, { body: data }) => {
data = JSON.parse(data);
console.log(data.currently);
});
This code snippet comes from an online course on NodeJS. I was messing around with the code (I didn't supply the secret API key) but I was curious to try and accomplish two lines of code into one statement, specifically I wanted to:
request({ url }, (error, { body: data }) => {
data = JSON.parse(data);
-Destructure the response ( which I accomplished using {body: data})
-JSON.parse the data
I am curious to know if it is possible to do these two things in the parameters where the response is located (second parameter).
Not elegantly. Destructuring is only intended to extract properties of existing objects into variables, but not to do additional processing. It's possible, using a hack, by using a 3rd parameter (which the request
doesn't provide), which gets defaulted to the JSON.parse
d data
:
const url = 'https://jsonplaceholder.typicode.com/todos/1';
request({ url }, (error, { body: data }, parsedData = JSON.parse(data)) => {
console.log(parsedData);
});
But that's confusing, and shouldn't be done.
Another similar method, without a 3rd parameter, but using a non-existent property of the response object:
request({ url }, (error, { body: data, parsedData = JSON.parse(data) }) => {
console.log(parsedData);
});
But these are just silly tricks. Parsing the JSON on the first line of the callback is definitely the right way to do this sort of thing.
Another option, which you might or might not find to be more elegant, is to use node-fetch. With it, you can call .json()
on the Response object instead, indicating that the it should be parsed as JSON rather than as text (for plain text, you'd use .text()
):
const fetch = require('node-fetch');
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetch(url)
.then(res => res.json())
.then((obj) => {
console.log(obj);
});