Use the HTTP GET method to retrieve information from a database of weather records. Query https://jsonmock.hackerrank.com/api/weather/search?name={keyword} to search all records where name contains the keyword anywhere in its string value. The query result is paginated and can be further accessed by appending &page=num where num is the page number.
The query response from the API is a JSON with the following five fields:
page: the current pageper_page: the maximum number of results per pagetotal: the total number of records in the search resulttotal_pages: the total number of pages to query to get all the resultsdata: an array of JSON objects that contain weather records
The data field contains weather records with the following schema:
name: the name of the cityweather: temperature recordedstatus: an array of wind speed and humidity records
Filter records to include a given keyword in the name parameter. Return an array such that each element is a string of comma-separated values:
city_name, temperature, wind, humidity
For example, the JSON record is stored as:
Adelaide,15,8,61
Return the list sorted by city name.
Complete the function weatherStation(keyword).
Parameters:
string keyword: the string to search
Returns:
string[]: the weather data for each city
这道题考察分页 API 的遍历、字段解析和结果排序。需要用 keyword 去请求天气搜索接口,循环读取所有 page,把每条记录中的城市名、weather 温度以及 status 数组里的风速和湿度提取出来,拼成 city_name,temperature,wind,humidity 的字符串数组,最后按城市名排序返回。关键点是不要只处理第一页,要根据 total_pages 把所有分页都拉完,再用字符串解析或正则从 status 中拆出两个数字。