概要
Golangにて、標準ライブラリの使用でJsonから特定の値だけを取り出すことは可能ですが、interface型なので値の取り出しが少し面倒です。何か良いライブラリがないかと探していたところ、json-iterator/goというものを見つけました。
json-iterator/go
は標準のライブラリよりも処理が速そうなのと、こちらのサンプルにある通り、Jsonから特定の値を取り出すこともできそうです。今回はこのJsonから特定の値を取り出す部分の実装サンプルを紹介します。
実装サンプルの前提とするJson
以前に【OpenWeatherAPI】リクエスト・レスポンスの項目に関するメモ書きで紹介した、OpenWeatherAPIのレスポンスを今回の題材にしたいと思います。
{
"cod": "200",
"message": 0,
"cnt": 40,
"list": [
{
"dt": 1650790800,
"main": {
"temp": 17.04,
"feels_like": 16.39,
"temp_min": 17.04,
"temp_max": 17.04,
"pressure": 1014,
"sea_level": 1014,
"grnd_level": 1013,
"humidity": 61,
"temp_kf": 0
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": { "all": 100 },
"wind": { "speed": 2.46, "deg": 15, "gust": 2.72 },
"visibility": 10000,
"pop": 0.54,
"rain": { "3h": 0.2 },
"sys": { "pod": "d" },
"dt_txt": "2022-04-24 09:00:00"
},
・
・
・
]
}
実装サンプル
上記のjsonから、dt
、weather
のicon
、feels_like
、rain
の3h
を取り出してみます。
func getWeatherResponseStrJSONConvert(jsonStr string) {
// Json文字列からオブジェクトに変換
weatherJson := jsoniter.Get([]byte(jsonStr))
// list項目を取得
weatherJsonList := weatherJson.Get("list")
// 動的型付けっぽい振る舞いをするのでサイズの取得ができる
for i := 0; i < weatherJsonList.Size(); i++ {
// 配列項目の場合はindex指定ができる
response := weatherJsonList.Get(i)
// dtの取得
unixTime: = response.Get("dt").ToInt64()
// weatherのiconの取得
weatherIcon = response.Get("weather").Get(0).Get("icon").ToString()
// feels_likeの取得
weatherInfo.TempFeelsLike = response.Get("main").Get("feels_like").ToFloat64()
// rainは特定条件のみ現れる項目のため、存在判定のためにまずはstringで取得
var rainFall *float64
rainFallStr := response.Get("rain").Get("3h").ToString()
if rainFallStr != "" {
rainFallFloat := response.Get("rain").Get("3h").ToFloat64()
rainFall = &rainFallFloat
}
・
・
・
}
}