douyin7829 2013-07-03 15:58
浏览 1104
已采纳

如何在Go中从json字符串获取键值

I would like to try get the key values from JSON in Go, however I'm unsure how to.

I've been able to use simplejson to read json values, however I've not been able to find out how to get the key values.

Would anyone be able to point me in the right direction and/or help me?

Thank you!

  • 写回答

3条回答 默认 最新

  • doujieju0397 2013-07-03 16:17
    关注

    You can get the top-level keys of a JSON structure by doing:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    // your JSON structure as a byte slice
    var j = []byte(`{"foo":1,"bar":2,"baz":[3,4]}`)
    
    func main() {
    
        // a map container to decode the JSON structure into
        c := make(map[string]interface{})
    
        // unmarschal JSON
        e := json.Unmarshal(j, &c)
    
        // panic on error
        if e != nil {
            panic(e)
        }
    
        // a string slice to hold the keys
        k := make([]string, len(c))
    
        // iteration counter
        i := 0
    
        // copy c's keys into k
        for s, _ := range c {
            k[i] = s
            i++
        }
    
        // output result to STDOUT
        fmt.Printf("%#v
    ", k)
    
    }
    

    Note that the order of the keys must not correspond to the their order in the JSON structure. Their order in the final slice will even vary between different runs of the exact same code. This is because of how map iteration works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器