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

Pat*_*ick 4 json go

我想尝试从Go中获取JSON的关键值,但是我不确定如何.

我已经能够使用simplejson来读取json值,但是我无法找到如何获取键值.

有人能指出我正确的方向和/或帮助我吗?

谢谢!

thw*_*hwd 9

您可以通过执行以下操作来获取JSON结构的顶级键:

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\n", k)

}
Run Code Online (Sandbox Code Playgroud)

请注意,键的顺序必须与JSON结构中的顺序不对应.它们在最终切片中的顺序甚至会在完全相同的代码的不同运行之间变化.这是因为地图迭代的工作原理.


fia*_*jaf 6

If you don't feel like writing tens of useless structs, you could use either

  1. https://github.com/jmoiron/jsonq

    q := jsonq.NewQuery(`{"object": {"collection": [{"items": ["hello"]}]}}`)
    q.String("object", "collection", "items", "0") // -> "hello"
    
    Run Code Online (Sandbox Code Playgroud)
  2. https://github.com/tidwall/gjson

    gjson.Get(
      `{"object": {"collection": [{"items": ["hello"]}]}}`,
      "object.collection.items.0",
    ) // -> "hello"
    
    Run Code Online (Sandbox Code Playgroud)

    Plus some weird-useful querying tricks.

  • 我现在绝对推荐 gjson 而不是 jsonq。jsonq 无人维护,并且支持非常有限(例如没有顶级数组) (2认同)