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条)

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备