Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

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!

like image 292
Patrick Avatar asked Jul 03 '13 15:07

Patrick


People also ask

How can I get the key-value in a JSON object?

To get the key and value from a JSON string you can use the JSON. parse() method it will convert the JSON string to a JSON object and you can easily get key and value.

How do I read JSON data in Golang?

json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.

How do I access JSON in Go?

In the main.go file, you'll add a main function to run your program. Next, you'll add a map[string]interface{} value with various keys and types of data. Then, you'll use the json. Marshal function to marshal the map data into JSON data.

How do I decode JSON in Golang?

Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct.


2 Answers

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]json.RawMessage)

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

}

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.

like image 79
thwd Avatar answered Nov 12 '22 05:11

thwd


If you don't feel like writing tens of useless structs, you could use something like https://github.com/tidwall/gjson:

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

Plus some weird-useful querying tricks.

like image 30
fiatjaf Avatar answered Nov 12 '22 05:11

fiatjaf