简体   繁体   中英

How to combine two json response and send it as a whole?

I am using zomato API which sends only 20 names in one api call and I want atleast 60 responses so I thought of calling the same api three times and combining all the responses together.

app.get('/locations/:query', async (req, res) => {
  const query = req.params.query;
  const data = await zomato.cities({ q: query,count: 1 })
  const cityId= await (data[0].id);
  const restaurants1 = await zomato.search({ entity_id: cityId, entity_type: 'city', start:0, count:20, sort:'rating', order:'desc' })
  const restaurants2 = await zomato.search({ entity_id: cityId, entity_type: 'city', start:20, count:40, sort:'rating', order:'desc' })
  const restaurants =  Object.assign(restaurants1,...restaurants2);
  res.send(restaurants);
  
})

As of now I have only tried till 40 but even this does not work. If another constant restaurant3 is there which has start 40 and end 60, how do I merge these three and send them back?

You shouldn't be spreading restaurants2 in your Object.assign() . Use one of the following:

const restaurants = Object.assign(restaurants1, restaurants2);

// or

const restaurants = { ...restaurants1, ...restaurants2 };

I haven't worked with zomato-api before but according to their API-documentation , you should be able to do this:

app.get('/locations/:query', async (req, res) => {
  const query = req.params.query;
  const data = await zomato.cities({ q: query,count: 1 })
  const cityId= data[0].id;
  const result = [];
  const nrOfRequests = 2; // change this accordingly to increase the nr of requests
  let currCount = 0;  
  const nrOfEntries = 20;
  for(let i=0; i < nrOfRequests ; i++) {
    const response = await zomato.search({ entity_id: cityId, entity_type: 'city', start:currCount, count:nrOfEntries, sort:'rating', order:'desc' });
    result.push(...response.restaurants);
    currCount += nrOfEntries;
  }      
  res.send(result);      
});

Basically you should be able to loop for the desired amount of requests by updating the start parameter for each iteration and then storing the resulting restaurants in your result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM