I have JSON like this:
{
"store_name": "Barry's Farmer's Market",
"foods": {
"apple": "5.91",
"peach": "1.84",
"carrot": "6.44",
"beans": "3.05",
"orange": "5.75",
"cucumber": "6.42"
},
"store_location": "Corner of Elm Tree Hill and 158th Street"
}
And I want to parse it as an unknown JSON using a map[string]interface{}
:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func main() {
var parsed map[string]interface{}
f, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
}
err = json.Unmarshal(f, &parsed)
for k, v := range parsed {
//fmt.Println(parsed["foods"])
fmt.Println(k + string(v))
}
}
Considering that "v" doesn't convert to string and that I want to range all the values in "foods", can you help me? I think i'm missing something...
If you read the documentation for json.Unmarshal
, you can see what types it will use, and base your code on that; or use fmt.Printf("%T",v)
to see what type it is at runtime.
err = json.Unmarshal(f, &parsed)
for k, v := range parsed["foods"].(map[string]interface{}) {
fmt.Println(k, v)
}
Working playground example: https://play.golang.org/p/nczV5qA41h
You could just make a structure which contains a map[string]string
and iterate over that. https://play.golang.org/p/IVlrTTcrVB
type Store struct {
Name string `json:"store_name"`
Foods map[string]string `json:"foods"`
Location string `json:"store_location"`
}
func main() {
var store Store
data := []byte(jsonData)
err := json.Unmarshal(data, &store)
if err != nil {
panic(err)
}
for k, v := range store.Foods {
fmt.Println(k + string(v))
}
}
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