MST

星途 面试题库

面试题:Bash脚本中如何调用简单API并处理返回数据

假设存在一个简单的天气API,其接口为http://api.example.com/weather?city={city_name} ,返回的是JSON格式数据。请编写一个Bash脚本,能够接收用户输入的城市名,调用该API,并从返回的JSON数据中提取出当前温度并打印出来。可使用curl命令来调用API,处理JSON数据可考虑使用jq工具(假设已安装)。
37.1万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

read -p "请输入城市名: " city_name

weather_info=$(curl -s "http://api.example.com/weather?city=$city_name")
current_temperature=$(echo "$weather_info" | jq -r '.current_temperature')

echo "当前温度: $current_temperature"

上述脚本中:

  1. read -p "请输入城市名: " city_name 提示用户输入城市名,并将输入赋值给 city_name 变量。
  2. curl -s "http://api.example.com/weather?city=$city_name" 调用天气API,-s 选项表示静默模式,不显示进度条等信息。
  3. echo "$weather_info" | jq -r '.current_temperature' 使用 jq 工具从返回的JSON数据中提取 current_temperature 字段的值,-r 选项表示以原始字符串形式输出。
  4. 最后打印出当前温度。

请根据实际API返回的JSON结构调整 jq 命令中的字段名。