Home >Backend Development >Golang >Golang: Get only one object in JSON collection response

Golang: Get only one object in JSON collection response

WBOY
WBOYforward
2024-02-15 12:54:09390browse

Golang:在 JSON 集合响应中仅获取一个对象

php editor Banana brings you an introduction to Golang’s ability to obtain only one object in a JSON collection response. When processing JSON data, sometimes we only need to obtain one of the objects instead of the entire collection. In this case, we can use some simple methods to achieve this. This article will introduce you in detail how to use Golang to achieve this requirement, allowing you to process JSON data more flexibly. Whether you are a beginner or an experienced developer, you can get practical tips and methods from this article. Let’s explore together!

Question content

Suppose I have a json response body as shown below:

{
   value: [{object a's key-values}, {object b's key-values}, {object c's key-values} ...]
}

Where objects a, b, c have different structures, although they may have the same key name. (For example, both obj a and b can have key "b", but only obj a has key "a")

I am only interested in object a in 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
}

Is unmarshalling the response into mydata valid? Can we specify a specific type of slice so that only the required elements with the correct structure are unmarshalled and the rest of the objects in the json collection are ignored?

Solution

First: you need to export the structure members:

type myobject struct{
    a string `json:"a"`
    b string `json:"b"`
}
type mydata struct{
   value []myobject `json:"value"`
}

You can then unmarshal the array using:

var v mydata
json.unmarshal(input,&v)

This will create an instance of myobject for each array element in the input, but only those elements with a and b fields will be populated. So you can filter for ones containing a:

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

The above is the detailed content of Golang: Get only one object in JSON collection response. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete