Search code examples
jsonparsinggointerfacemarshalling

Reading the data which is in a map[string]interface{}


Source server return the data in a Json format of multiple object interfaces, how can we parse such data ?

I am using a variable of JSON map[string]interface{} type to hold the result from server

 The data return from Server.
"data": [
       {
        "group": "PAA_TEST",
        "id": "2018-04-10T09:24:18.000000Z",
        "name": "PAA_STATION",
        "released": true,
        "version": 33
    },
    {
        "group": "PAA_TEST",
        "id": "2018-03-19T10:50:21.000000Z",
        "name": "PAA_STATION",
        "released": false,
        "version": 32
    }

my fmt.print output outputdata["data"] //where output data is of JSON map[string]interface{}

    [
       map[group:PAA_TEST id:2018-04-10T09:24:18.000000Z name:PAA_STATION 
       released:true version:33] 
       map[group:PAA_TEST id:2018-03-19T10:50:21.000000Z name:PAA_STATION 
       released:false version:32] 
   ]

How can we iterate with multiple Map interfaces? For example, if I just want to process the information with released status as true. I am trying various method for indexing but no luck yet.


Solution

  • The best solution is to decode the JSON directly to a Go type that matches the structure of the data. This avoids the type assertions required to dig through a map[string]interface{}.

    I'll assume that the common function looks something like this:

    func request(path string, ... more arguments) (map[string]interface{}}, error) {
          ...
          resp, err := client.Do(req)
          if err != nil {
             return nil, err
          }
          defer resp.Body.Close()
          ...
          var result map[string]interface{}
          err := json.NewDecoder(resp.Body).Decode(&result)
          return result, err
    }
    

    Change the function to take a pointer to the result as an argument:

    func request(pv interface{}, path string, ... more arguments) error {
          ...
          resp, err := client.Do(req)
          if err != nil {
             return err
          }
          defer resp.Body.Close()
          ...
          err := json.NewDecoder(resp.Body).Decode(pv)
          return err
    }
    

    Call this modified function like this:

    var result struct { 
        Data []struct{ 
            Group, ID, Name string
            Released bool
            Version int 
        }
    }
    err := request(&result, "some/path", ... more arguments )
    if err != nil {
        // handle error
    }
    
    for _, d := range result.Data {
       if !d.Released {
           continue
       }
       fmt.Println(d.Group, d.ID, d.Name, d.Version)
       ... process d
    }