Golang: Getting only one object in a JSON collection response

huangapple go评论79阅读模式
英文:

Golang: Getting only one object in a JSON collection response

问题

假设我有一个类似以下结构的JSON响应体:

{
   value: [{对象A的键值对}, {对象B的键值对}, {对象C的键值对} ...]
}

其中对象A、B、C具有不同的结构,尽管它们可能具有相同的键名(例如,对象A和B都可能具有键"b",但只有对象A具有键"a")。

我只对JSON响应中的对象A感兴趣,其余部分可以丢弃。如果我有以下结构:

type MyObject struct{
    a string
    b string
}

type MyData struct{
   value []MyObject
}

将响应解组成MyData结构是否可行?我们是否可以指定一个特定类型的切片,以便只有具有正确结构的所需元素被解组,而JSON集合中的其他对象被忽略?

英文:

Suppose I have have a JSON response body that looks something like this:

{
   value: [{Object A's key-values}, {Object B's key-values}, {Object C's key-values} ...]
}

Where Object A, B, C are of different structures, although they may have same key names. (e.g. both Obj A and B could have the key "b", but only Obj A has the key "a")

I am only interested in Object A from the JSON response, the rest can be discarded. If I have a structure like this:

type MyObject struct{
    a string
    b string
}

type MyData struct{
   value []MyObject
}

Will unmarshalling the response into MyData work? Can we specify a slice of a particular type such that only the desired element with the correct structure gets unmarhshalled and the rest of the objects in the JSON collection gets ignored?

答案1

得分: 2

首先,你需要导出结构体成员:

type MyObject struct{
    A string `json:"a"`
    B string `json:"b"`
}
type MyData struct{
   Value []MyObject `json:"value"`
}

然后,你可以使用以下代码对数组进行解组:

var v MyData
json.Unmarshal(input, &v)

这将为输入中的每个数组元素创建一个MyObject实例,但只有那些具有ab字段的实例将被填充。因此,你可以筛选包含a的实例:

for _, x := range v.Value {
   if x.A != "" {
     ///
   }
}
英文:

First: you need to export struct members:

type MyObject struct{
    A string `json:"a"`
    B string `json:"b"`
}
type MyData struct{
   Value []MyObject `json:"value"`
}

Then, you can unmarshal the array using:

var v MyData
json.Unmarshal(input,&v)

This will create a MyObject instance for every array element in the input, but only those that have a and b fields will be populated. Thus, you can filter the ones containing a:

for _,x:=range v.Values {
   if x.A!="" {
     ///
   }
}

huangapple
  • 本文由 发表于 2023年2月3日 10:21:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75330871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定