1

How can I convert an API response from string to an array of objects?

I am making a GET call as follows and the result I get is returned as one very long string:

const state = {
    strict: true,
    airports: []
};

const getters = {
    allAirports: (state) => state.airports,
};

const actions = {
    getAirports({ commit }) {
        axios.get('https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat')
            .then(response => {
                commit('SET_AIRPORTS', response.data)
            })
    }
};

const mutations = {
    SET_AIRPORTS(state, airports) {
        state.airports = airports
    }
};

And the response is:

1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291,5282,10,"U","Pacific/Port_Moresby","airport","OurAirports" 2,"Madang Airport","Madang","Papua New Guinea","MAG","AYMD",-5.20707988739,145.789001465,20,10,"U","Pacific/Port_Moresby","airport","OurAirports" 3,"Mount Hagen Kagamuga Airport","Mount Hagen","Papua New Guinea","HGU","AYMH",-5.826789855957031,144.29600524902344,5388,10,"U","Pacific/Port_Moresby","airport","OurAirports" 4,"Nadzab Airport","Nadzab","Papua New Guinea","LAE","AYNZ",-6.569803,146.725977,239,10,"U","Pacific/Port_Moresby","airport","OurAirports" 5,"Port Moresby Jacksons International Airport","Port Moresby","Papua New Guinea","POM","AYPY",-9.443380355834961,147.22000122070312,146,10,"U","Pacific/Port_Moresby","airport","OurAirports" 6,"Wewak International Airport","Wewak","Papua New Guinea","WWK","AYWK",-3.58383011818,143.669006348,19,10,"U","Pacific/Port_Moresby","airport","OurAirports" 7,"Narsarsuaq Airport","Narssarssuaq","Greenland","UAK","BGBW",61.1604995728,-45.4259986877,112,-3,"E","America/Godthab","airport","OurAirports" 8,"Godthaab / Nuuk Airport","Godthaab","Greenland","GOH","BGGH",64.19090271,-51.6781005859,283,-3,"E","America/Godthab","airport","OurAirports" 9,"Kangerlussuaq Airport","Sondrestrom","Greenland","SFJ","BGSF",67.0122218992,-50.7116031647,165,-3,"E","America/Godthab","airport","OurAirports"

However, my goal is that once the call is made, this string is divided in several objects and added to the airports array as follows:

airports: [
  {
   id: 1,
   name: 'Goroka Airport',
   city: 'Goroka',
   country: 'Papua New Guinea',
   iata: 'GKA',
   icao: 'AYGA',
   longitude: -6.081689834590001,
   latitude: 145.391998291
  }
  {
   etc...
  }
]

Can you please advise how can I achieve the above?

1

3 Answers 3

1

Try this, Written in simple and understandable code

var WholeString = [1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291,5282,10,"U","Pacific/Port_Moresby","airport","OurAirports",2,"Madang Airport","Madang","Papua New Guinea","MAG","AYMD",-5.20707988739,145.789001465,20,10,"U","Pacific/Port_Moresby","airport","OurAirports"];


var fullarray = WholeString;    //.split(',');

var i = 0;
var airportArray = []; 

fullarray.forEach(function callbackFn(value, index) {

  if (typeof airportArray[i] == 'undefined') {
    airportArray[i] = [];
  }
    
  airportArray[i].push(value);
  
  if((index+1)%14==0 && index!=0)
  {
    i++;
  }

});


var j = 0;
var finalArr = [];
airportArray.forEach(function callbackFn(value, index) {
    finalArr.push({
        id: value[0],
        name: value[1],
        city: value[2],
        country: value[3],
        iata: value[4],
        icao: value[5],
        longitude: value[6],
        latitude: value[7],
    });

});


console.log(finalArr);

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

Comments

0
  1. To get the individual lines of data, use String.prototype.split() with \n as the separator on the text response from the URL.

  2. Use Array.prototype.map() to convert each line:

    a. Parse the comma-separated fields from the line by using String.prototype.split() with , as the separator.

    b. Strip redundant quotes from the fields by using String.prototype.replace() with a regular expression that matches leading/trailing quotes and an empty string as the replacement.

    c. Return an object with the desired named fields.

const actions = {
  getAirports({ commit }) {
    axios
      .get('https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat')
      .then(response => {
        // 1️.
        const lines = response.data.split('\n');
        // 2️.
        const airports = lines.map(line => {
          const fields = line.split(',') // 2a.
                            .map(x => x.replace(/(^"|"$)/g, '')); // 2b.

          // 2c.
          return {
            id: fields[0],
            name: fields[1],
            city: fields[2],
            country: fields[3],
            iata: fields[4],
            icao: fields[5],
            longitude: fields[6],
            latitude: fields[7],
          };
        });

        commit('SET_AIRPORTS', airports);
      })
  }
};

demo

1 Comment

Hi Tony, thanks for the answer! I liked your approach the most, much appreciated!
0

if you are certain about the length of the object then you can try this

const prototype = {
   id: '',
   name: '',
   city: '',   
   country: '',
   iata: '',
   icao: '',
   longitude: '',
   latitude: ''
}
const arr = [1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291]
let chunked = []  //* final  output
let chunk = 8 //* chunk length



for (let i = 0; i< arr.length; i+=chunk) {
  let obj = {}
  let temp = arr.slice(i, i+chunk)
  
 
  Object.keys(prototype).map((key,i)=>{
     obj[key] = temp[i]
  })
  chunked = [...chunked,obj]
}


console.log(chunked)

const prototype = {
   id: '',
   name: '',
   city: '',   
   country: '',
   iata: '',
   icao: '',
   longitude: '',
   latitude: ''
}
const arr = [1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291]
let chunked = []  //* final  output
let chunk = 8 //* chunk length



for (let i = 0; i< arr.length; i+=chunk) {
  let obj = {}
  let temp = arr.slice(i, i+chunk)
  
 
  Object.keys(prototype).map((key,i)=>{
     obj[key] = temp[i]
  })
  chunked = [...chunked,obj]
}


console.log(chunked)

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.