Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing unknown JSON from file and iterate into it

Tags:

json

go

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

like image 720
Blallo Avatar asked Mar 09 '23 04:03

Blallo


2 Answers

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

like image 190
Adrian Avatar answered Mar 10 '23 17:03

Adrian


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))
    }
}
like image 25
J.Timblin Avatar answered Mar 10 '23 17:03

J.Timblin