Golang: Get only one object in JSON collection response

WBOY
Release: 2024-02-15 12:54:09
forward
389 people have browsed it

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} ...]
}
Copy after login

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
}
Copy after login

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"`
}
Copy after login

You can then unmarshal the array using:

var v mydata
json.unmarshal(input,&v)
Copy after login

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!="" {
     ///
   }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template