如何在Golang中根据条件从JSON对象数组中获取值?

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

How do I get values from an array of json objects based on a condition in golang?

问题

我有一个像这样的数组。

[{
    "seq" : 2,
    "amnt" : 125
},
{
    "seq" : 3,
    "amnt" : 25
},
{
    "seq" : 2,
    "amnt" : 250
}]

我需要从这个数组中获取seq为2的对象。

在Linq中,我们有扩展方法可以设置条件。

在Go中,我需要通过for循环遍历并获取它,还是有其他方法?

请给我提供一个最佳的方法。

**注意:**这个JSON有很多字段,对于这个例子,我只给出了两个。

我是Go的新学习者。

英文:

I have an array like this.

[{
    "seq" : 2,
    "amnt" : 125
},
{
    "seq" : 3
    "amnt" : 25
},
{
    "seq" : 2
    "amnt" : 250
}]

I need to fetch objects from this array where seq is 2.

In Linq we have extensions in which I can put a where condition.

In Go do I need to loop through and get it using for loop or is there another way?

Please suggest me an optimum way.

Note: The json has many fields, for this example I gave only two.

I'm a new learner of Go.

答案1

得分: 2

我不知道“最佳”方法,但是以下是你现在可以采取的步骤来继续进行:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	byt := []byte(`[{"seq": 2,"amnt": 125},{"seq": 3,"amnt": 25},{"seq": 2,"amnt": 250}]`)

	var dat []map[string]int

	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}

	for idx := range dat {

		if dat[idx]["seq"] == 2 {
			fmt.Println("bingo")
		}
	}
}

祝你好运

**编辑**在我第一个答案中我假设你可能有非数字值所以我使用了`interface{}`类型但在@JimB的建议下我将其更改为仅寻找`int`类型因此如果你的JSON数据中有一些`string`或其他类型解组将失败

<details>
<summary>英文:</summary>

I dont know about &#39;optimal&#39; way to do this but here is what you can do for now to move forward:


    package main
    
    import (
    	&quot;encoding/json&quot;
    	&quot;fmt&quot;
    )
    
    func main() {
    	byt := []byte(`[{&quot;seq&quot;: 2,&quot;amnt&quot;: 125},{&quot;seq&quot;: 3,&quot;amnt&quot;: 25},{&quot;seq&quot;: 2,&quot;amnt&quot;: 250}]`)
    
    	var dat []map[string]int
    
    	if err := json.Unmarshal(byt, &amp;dat); err != nil {
    		panic(err)
    	}
    
    	for idx := range dat {
    		
    		if dat[idx][&quot;seq&quot;] == 2 {
    			fmt.Println(&quot;bingo&quot;)
    		}
    	}
    }

Goodluck.

**Edit:** in my first answer I assumed that you might have non-numeric values so that&#39;s why I used `interface{}` type but after @JimB suggestion I changed that to seek only `int` type, so if you have to have some `string` or any other type in you json payload the unmarshaling will fail.

</details>



huangapple
  • 本文由 发表于 2014年3月5日 19:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/22196484.html
匿名

发表评论

匿名网友

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

确定