简体   繁体   English

在golang中解组平面和嵌套jsons

[英]Unmarshall both flat and nested jsons in golang

Say I want to be able to handle both nested and unnested json s of the following form, as in this example: 假设我希望能够处理以下形式的嵌套和未嵌套json ,如本例所示:

source_json_1 := `{"owner": "John", "nickname": "Rose", "species": "Dog"}`
source_json_2 := `{"owner": "Doe", "Pet": [{"nickname": "Rose", "species": "Dog"},
                                          {"nickname": "Max", "species": "Cat"}]}`

If I define Pet as an embedded struct I can easily unmarshal it with: 如果我将Pet定义为嵌入式结构,则可以轻松地将其解组:

type Owner struct {
    Name string
    Pet
}

type Pet struct {
    NickName    string
    Species     string
}

Resulting in John's pet getting adequately marshalled. 导致约翰的宠物被适当地整理。

{John {Rose Dog}}
{Doe { }}

But since Pet can actually also be a slice of Pet s, Doe's Pet s are not correctly unmarshalled. 但是,由于Pet实际上也可以是Pet的一部分,因此没有正确地解编Doe的Pet If instead go with 如果相反

type Owner struct {
    Name string
    Pet  []Pet
}

Then Doe gets marshalled just fine. 然后,美国能源部被整理好。

{John []}
{Doe [{Rose Dog} {Max Cat}]}

How can I catch both cases? 我怎样才能抓住这两种情况?

I'd prefer to marshall it into a slice of Pet s in the end, no matter what. 最后,无论如何,我都希望将其编组为Pet的一部分。

You're looking at two separate data structures, so to unmarshal them with a single struct type, you'd need to account for both: 您正在查看两个单独的数据结构,因此要使用单个struct类型将其解组,则需要考虑这两个:

type Owner struct {
    Name string
    Pet
    Pets []Pet `json:"Pet"`
}

Then, if you want the slice to be authoritative, after you unmarshall, move the embedded to the slice: 然后,如果要使切片具有权威性,则在解组后,将嵌入的内容移至切片:

// owner := unmarshall blah blah
if owner.Pet != Pet{} {
    owner.Pets = append(owner.Pets, owner.Pet)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM