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!
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With