duanchen7036 2014-03-05 11:31
浏览 418
已采纳

如何基于golang中的条件从json对象数组中获取值?

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条回答 默认 最新

  • dphj737575 2014-03-05 12:39
    关注

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

    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")
            }
        }
    }
    

    Goodluck.

    Edit: in my first answer I assumed that you might have non-numeric values so that'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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: