
不明なキーを含むネストされた JSON を解明する
JSON の複雑さを解明する
未知のキーと複雑なネスト構造を含む JSON データに遭遇することは、気の遠くなるような作業になる可能性があります。次の JSON 形式を考えてみましょう:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | {
"message" : {
"Server1.example.com" : [
{
"application" : "Apache" ,
"host" : {
"name" : "/^Server-[13456]/"
},
"owner" : "User1" ,
"project" : "Web" ,
"subowner" : "User2"
}
],
"Server2.example.com" : [
{
"application" : "Mysql" ,
"host" : {
"name" : "/^Server[23456]/"
},
"owner" : "User2" ,
"project" : "DB" ,
"subowner" : "User3"
}
]
},
"response_ms" : 659,
"success" : true
}
|
ログイン後にコピー
この例に示すように、サーバー名 (Server[0-9].example.com) は事前に決定されておらず、変更される可能性があります。さらに、サーバー名に続くフィールドには明示的なキーがありません。
ソリューションの構造
このデータを効果的に取得するには、map[string]ServerStruct 構造を使用できます。
1 2 3 4 5 6 7 8 9 10 11 | type YourStruct struct {
Success bool
ResponseMS int
Servers map[string]*ServerStruct
}
type ServerStruct struct {
Application string
Owner string
[...]
}
|
ログイン後にコピー
これらの構造を組み込むことで、マップへの不明なサーバー名の割り当てが可能になります。
JSON の秘密を明らかにする
JSON のアンマーシャリングをさらに効率的に行うには、必要な JSON タグを追加することを検討してください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import "encoding/json"
type YourStruct struct {
Success bool
ResponseMS int `json: "response_ms" `
Servers map[string]*ServerStruct `json: "message" `
}
type ServerStruct struct {
Application string `json: "application" `
Owner string `json: "owner" `
[...]
}
func (s *YourStruct) UnmarshalJSON(data []byte) error {
type YourStructHelper struct {
Success bool
ResponseMS int `json: "response_ms" `
Servers map[string]ServerStruct `json: "message" `
}
var helper YourStructHelper
if err := json.Unmarshal(data, &helper); err != nil {
return err
}
s.Success = helper.Success
s.ResponseMS = helper.ResponseMS
s.Servers = make(map[string]*ServerStruct)
for k, v := range helper.Servers {
s.Servers[k] = &v
}
return nil
}
|
ログイン後にコピー
これらの調整により、提供された JSON をカスタム構造体に効果的にアンマーシャリングし、簡単なデータ操作への道を開くことができます。
以上が不明なキーを使用してネストされた JSON をアンマーシャリングするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。