1

I'm trying to get data from API and write it in Json File. How can I do that please?
the function to retrive the data is:

 function get_flights_by_airport(airport_name, callback) {
    let request = require('request');
    let url = 'http://api.aviationstack.com/v1/flights?access_key=xxxx'
    request(url, function (err, response, body) {
      if (err) {
        console.log('error:', error);
        callback(err);
      } else {
        let vol = JSON.parse(body)
        num = vol.pagination.count
        result = []
        for (let i = 0; i < num; i++) {
          dep = vol.data[i].departure.airport
          one_flight = {number: vol.data[i].flight.number, date: vol.data[i].flight_date, departure: vol.data[i].departure.timezone, arrival: vol.data[i].arrival.timezone, from: vol.data[i].departure.airport, to: vol.data[i].arrival.airport}
          result.push(one_flight)
         
          }
        callback(null, result)
      }
   });}
2
  • 1
    You could check the filesystem module fs. It has APIs like writeFile and writeFileSync which could be used to write to a file. And use JSON.stringify to convert your JSON object to a string before writing it. Commented Nov 22, 2020 at 16:58
  • 1
    Hi Mariem. Please check the answer and mark the question as answered if it so. Thanks! Commented Apr 22, 2021 at 8:42

1 Answer 1

1

You should use the fs module. The fs module enables interacting with the file system in a way modeled on standard POSIX functions. All file system operations have synchronous, callback, and promise-based forms.

Here is an example of the synchronous way to write file

const fs = require('fs');


fs.writeFileSync(`${FILE_PATH}.json`, JSON.stringify(YOUR_JSON));

Replace FILE_PATH to the path where you want to save the file and YOUR_JSON to your JSON.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.