未知構造のJSONデータを復号する
1881 ワード
未知の構造のJSONを復号するには、このJSONデータを空のインタフェースに復号するだけでよい.JSONデータを復号する過程で、JSONデータの中の要素タイプは次のように変換されます.
1)JSONのブール値はGoのboolタイプに変換されます.
2)数値はGoのfloat 64型に変換される.
3)文字列変換後もstringタイプです.
4)JSON配列は[]interface{}タイプに変換されます.
5)JSONオブジェクトはmap[string]interface{}タイプに変換されます.
6)null値はnilに変換されます.
Goの標準ライブラリencoding/jsonパッケージでは、map[string]interface{}と[]interface{}タイプの値を使用して、未知の構造のJSONオブジェクトまたは配列をそれぞれ格納できます.サンプルコードは次のとおりです.
出力結果
1)JSONのブール値はGoのboolタイプに変換されます.
2)数値はGoのfloat 64型に変換される.
3)文字列変換後もstringタイプです.
4)JSON配列は[]interface{}タイプに変換されます.
5)JSONオブジェクトはmap[string]interface{}タイプに変換されます.
6)null値はnilに変換されます.
Goの標準ライブラリencoding/jsonパッケージでは、map[string]interface{}と[]interface{}タイプの値を使用して、未知の構造のJSONオブジェクトまたは配列をそれぞれ格納できます.サンプルコードは次のとおりです.
package main
import (
"fmt"
"encoding/json"
)
func main() {
b := []byte(`{"Title":"Go ","Authors":["XuShiwei","HughLv","Pandaman","GuaguaSong","HanTuo","BertYuan","XuDaoli"],"Publisher":"ituring.com.cn","IsPublished":true,"Price":9.99,"Sales":1000000}`)
var r interface{}
err := json.Unmarshal(b, &r)
if err == nil {
fmt.Println(r)
}
gobook, ok := r.(map[string]interface{})
if ok {
for k, v := range gobook {
switch v2 := v.(type) {
case string:
fmt.Println(k, "is string", v2)
case int:
fmt.Println(k, "is int", v2)
case bool:
fmt.Println(k, "is bool", v2)
case []interface{}:
fmt.Println(k, "is an array:")
for i, iv := range v2 {
fmt.Println(i, iv)
}
default:
fmt.Println(k, "is another type not handle yet")
}
}
}
}
出力結果
map[Publisher:ituring.com.cn IsPublished:true Price:9.99 Sales:1e+06 Title:Go Authors:[XuShiwei HughLv Pandaman GuaguaSong HanTuo BertYuan XuDaoli]]
IsPublished is bool true
Price is another type not handle yet
Sales is another type not handle yet
Title is string Go
Authors is an array:
0 XuShiwei
1 HughLv
2 Pandaman
3 GuaguaSong
4 HanTuo
5 BertYuan
6 XuDaoli
Publisher is string ituring.com.cn