Patrick Patrick - 1 year ago 58
JSON Question

How to get the key value from a json string in Go

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!


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

package main

import (

// 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 {

    // 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

    // output result to STDOUT
    fmt.Printf("%#v\n", 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.