How to parse a nest json file with unknown structure Golang












-1















I am trying to parse and get selected data from a deep nested json data in Go Lang. I'm having issues navigating through the structure and accessing the data. The data is too deep and complex to be parsed with a-priori known structures in Go.
Here is the URL of the file:
-https://www.data.gouv.fr/api/1/datasets/?format=csv&page=0&page_size=20



I did some parsing with map interfaces and using a json string:



resultdata := map[string]interface {}

json.Unmarshal(byte(inputbytestring), &resultdata) //Inputstring is the string containing the JSON data of the above URL


The problem:




  • How can turn resultdata into a map (of strings), so I can use methods available for maps?

  • The JSON data is nested and has several levels. How is it possible to access the lower level JSON fields? is it possible to unmarshal the data recursively?










share|improve this question

























  • As @a-h said, the structure of the JSON is not very bad, and it's possible to compose a correspondent Go struct. If it wouldn't be the case and you can rely only on field names and types, then I would recommend parsing such JSON token by token

    – Andrey Dyatlov
    Jan 2 at 5:45


















-1















I am trying to parse and get selected data from a deep nested json data in Go Lang. I'm having issues navigating through the structure and accessing the data. The data is too deep and complex to be parsed with a-priori known structures in Go.
Here is the URL of the file:
-https://www.data.gouv.fr/api/1/datasets/?format=csv&page=0&page_size=20



I did some parsing with map interfaces and using a json string:



resultdata := map[string]interface {}

json.Unmarshal(byte(inputbytestring), &resultdata) //Inputstring is the string containing the JSON data of the above URL


The problem:




  • How can turn resultdata into a map (of strings), so I can use methods available for maps?

  • The JSON data is nested and has several levels. How is it possible to access the lower level JSON fields? is it possible to unmarshal the data recursively?










share|improve this question

























  • As @a-h said, the structure of the JSON is not very bad, and it's possible to compose a correspondent Go struct. If it wouldn't be the case and you can rely only on field names and types, then I would recommend parsing such JSON token by token

    – Andrey Dyatlov
    Jan 2 at 5:45
















-1












-1








-1








I am trying to parse and get selected data from a deep nested json data in Go Lang. I'm having issues navigating through the structure and accessing the data. The data is too deep and complex to be parsed with a-priori known structures in Go.
Here is the URL of the file:
-https://www.data.gouv.fr/api/1/datasets/?format=csv&page=0&page_size=20



I did some parsing with map interfaces and using a json string:



resultdata := map[string]interface {}

json.Unmarshal(byte(inputbytestring), &resultdata) //Inputstring is the string containing the JSON data of the above URL


The problem:




  • How can turn resultdata into a map (of strings), so I can use methods available for maps?

  • The JSON data is nested and has several levels. How is it possible to access the lower level JSON fields? is it possible to unmarshal the data recursively?










share|improve this question
















I am trying to parse and get selected data from a deep nested json data in Go Lang. I'm having issues navigating through the structure and accessing the data. The data is too deep and complex to be parsed with a-priori known structures in Go.
Here is the URL of the file:
-https://www.data.gouv.fr/api/1/datasets/?format=csv&page=0&page_size=20



I did some parsing with map interfaces and using a json string:



resultdata := map[string]interface {}

json.Unmarshal(byte(inputbytestring), &resultdata) //Inputstring is the string containing the JSON data of the above URL


The problem:




  • How can turn resultdata into a map (of strings), so I can use methods available for maps?

  • The JSON data is nested and has several levels. How is it possible to access the lower level JSON fields? is it possible to unmarshal the data recursively?







json dictionary go interface nested






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 at 17:20









Flimzy

39.5k116699




39.5k116699










asked Jan 1 at 17:04









Emmanuel DaugerasEmmanuel Daugeras

291




291













  • As @a-h said, the structure of the JSON is not very bad, and it's possible to compose a correspondent Go struct. If it wouldn't be the case and you can rely only on field names and types, then I would recommend parsing such JSON token by token

    – Andrey Dyatlov
    Jan 2 at 5:45





















  • As @a-h said, the structure of the JSON is not very bad, and it's possible to compose a correspondent Go struct. If it wouldn't be the case and you can rely only on field names and types, then I would recommend parsing such JSON token by token

    – Andrey Dyatlov
    Jan 2 at 5:45



















As @a-h said, the structure of the JSON is not very bad, and it's possible to compose a correspondent Go struct. If it wouldn't be the case and you can rely only on field names and types, then I would recommend parsing such JSON token by token

– Andrey Dyatlov
Jan 2 at 5:45







As @a-h said, the structure of the JSON is not very bad, and it's possible to compose a correspondent Go struct. If it wouldn't be the case and you can rely only on field names and types, then I would recommend parsing such JSON token by token

– Andrey Dyatlov
Jan 2 at 5:45














1 Answer
1






active

oldest

votes


















3














Once you have data as a map[string]interface{}, you can use type assertions to get to the lower levels of data.



There's a good explanation here of how to do this at https://blog.golang.org/json-and-go



Here's an example to get you most of the way:



https://play.golang.org/p/P8cGP1mTDmD



package main



import (
"encoding/json"
"fmt"
"log"
)

func main() {
jsonData := `{
"string": "string_value",
"number": 123.45,
"js_array": ["a", "b", "c"],
"integer": 678,
"subtype": {
"number_array": [1, 2, 3]
}
}`

m := map[string]interface{}{}
err := json.Unmarshal(byte(jsonData), &m)
if err != nil {
log.Fatal(err)
}

for key, value := range m {
switch v := value.(type) {
case int:
fmt.Printf("Key: %s, Integer: %dn", key, v)
case float64:
fmt.Printf("Key: %s, Float: %vn", key, v)
case string:
fmt.Printf("Key: %s, String: %sn", key, v)
case map[string]interface{}:
fmt.Printf("Key: %s, Subtype: %+vn", key, v)
case interface{}:
//TODO: Read through each item in the interface and work out what type it is.
fmt.Printf("Key: %s, interface: %vn", key, v)
default:
fmt.Printf("Key: %s, unhandled type: %+vn", key, v)
}
}
}


Alternatively https://mholt.github.io/json-to-go/ does a decent job of turning examples of JSON data into Go structs that can be used for marshalling.



Putting the example in, I get something that isn't too bad.



type AutoGenerated struct {
Data struct {
Acronym interface{} `json:"acronym"`
Badges interface{} `json:"badges"`
CreatedAt string `json:"created_at"`
Deleted interface{} `json:"deleted"`
Description string `json:"description"`
Extras struct {
} `json:"extras"`
Frequency string `json:"frequency"`
FrequencyDate interface{} `json:"frequency_date"`
ID string `json:"id"`
LastModified string `json:"last_modified"`
LastUpdate string `json:"last_update"`
License string `json:"license"`
Metrics struct {
Discussions int `json:"discussions"`
Followers int `json:"followers"`
Issues int `json:"issues"`
NbHits int `json:"nb_hits"`
NbUniqVisitors int `json:"nb_uniq_visitors"`
NbVisits int `json:"nb_visits"`
Reuses int `json:"reuses"`
Views int `json:"views"`
} `json:"metrics"`
Organization struct {
Acronym string `json:"acronym"`
Class string `json:"class"`
ID string `json:"id"`
Logo string `json:"logo"`
LogoThumbnail string `json:"logo_thumbnail"`
Name string `json:"name"`
Page string `json:"page"`
Slug string `json:"slug"`
URI string `json:"uri"`
} `json:"organization"`
Owner interface{} `json:"owner"`
Page string `json:"page"`
Private bool `json:"private"`
Resources struct {
Checksum struct {
Type string `json:"type"`
Value string `json:"value"`
} `json:"checksum"`
CreatedAt string `json:"created_at"`
Description interface{} `json:"description"`
Extras struct {
} `json:"extras"`
Filesize int `json:"filesize"`
Filetype string `json:"filetype"`
Format string `json:"format"`
ID string `json:"id"`
LastModified string `json:"last_modified"`
Latest string `json:"latest"`
Metrics struct {
NbHits int `json:"nb_hits"`
NbUniqVisitors int `json:"nb_uniq_visitors"`
NbVisits int `json:"nb_visits"`
Views int `json:"views"`
} `json:"metrics"`
Mime string `json:"mime"`
PreviewURL string `json:"preview_url"`
Published string `json:"published"`
Title string `json:"title"`
Type string `json:"type"`
URL string `json:"url"`
} `json:"resources"`
Slug string `json:"slug"`
Spatial interface{} `json:"spatial"`
Tags interface{} `json:"tags"`
TemporalCoverage interface{} `json:"temporal_coverage"`
Title string `json:"title"`
URI string `json:"uri"`
} `json:"data"`
Facets struct {
Format interface{} `json:"format"`
} `json:"facets"`
NextPage string `json:"next_page"`
Page int `json:"page"`
PageSize int `json:"page_size"`
PreviousPage interface{} `json:"previous_page"`
Total int `json:"total"`
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997328%2fhow-to-parse-a-nest-json-file-with-unknown-structure-golang%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    Once you have data as a map[string]interface{}, you can use type assertions to get to the lower levels of data.



    There's a good explanation here of how to do this at https://blog.golang.org/json-and-go



    Here's an example to get you most of the way:



    https://play.golang.org/p/P8cGP1mTDmD



    package main



    import (
    "encoding/json"
    "fmt"
    "log"
    )

    func main() {
    jsonData := `{
    "string": "string_value",
    "number": 123.45,
    "js_array": ["a", "b", "c"],
    "integer": 678,
    "subtype": {
    "number_array": [1, 2, 3]
    }
    }`

    m := map[string]interface{}{}
    err := json.Unmarshal(byte(jsonData), &m)
    if err != nil {
    log.Fatal(err)
    }

    for key, value := range m {
    switch v := value.(type) {
    case int:
    fmt.Printf("Key: %s, Integer: %dn", key, v)
    case float64:
    fmt.Printf("Key: %s, Float: %vn", key, v)
    case string:
    fmt.Printf("Key: %s, String: %sn", key, v)
    case map[string]interface{}:
    fmt.Printf("Key: %s, Subtype: %+vn", key, v)
    case interface{}:
    //TODO: Read through each item in the interface and work out what type it is.
    fmt.Printf("Key: %s, interface: %vn", key, v)
    default:
    fmt.Printf("Key: %s, unhandled type: %+vn", key, v)
    }
    }
    }


    Alternatively https://mholt.github.io/json-to-go/ does a decent job of turning examples of JSON data into Go structs that can be used for marshalling.



    Putting the example in, I get something that isn't too bad.



    type AutoGenerated struct {
    Data struct {
    Acronym interface{} `json:"acronym"`
    Badges interface{} `json:"badges"`
    CreatedAt string `json:"created_at"`
    Deleted interface{} `json:"deleted"`
    Description string `json:"description"`
    Extras struct {
    } `json:"extras"`
    Frequency string `json:"frequency"`
    FrequencyDate interface{} `json:"frequency_date"`
    ID string `json:"id"`
    LastModified string `json:"last_modified"`
    LastUpdate string `json:"last_update"`
    License string `json:"license"`
    Metrics struct {
    Discussions int `json:"discussions"`
    Followers int `json:"followers"`
    Issues int `json:"issues"`
    NbHits int `json:"nb_hits"`
    NbUniqVisitors int `json:"nb_uniq_visitors"`
    NbVisits int `json:"nb_visits"`
    Reuses int `json:"reuses"`
    Views int `json:"views"`
    } `json:"metrics"`
    Organization struct {
    Acronym string `json:"acronym"`
    Class string `json:"class"`
    ID string `json:"id"`
    Logo string `json:"logo"`
    LogoThumbnail string `json:"logo_thumbnail"`
    Name string `json:"name"`
    Page string `json:"page"`
    Slug string `json:"slug"`
    URI string `json:"uri"`
    } `json:"organization"`
    Owner interface{} `json:"owner"`
    Page string `json:"page"`
    Private bool `json:"private"`
    Resources struct {
    Checksum struct {
    Type string `json:"type"`
    Value string `json:"value"`
    } `json:"checksum"`
    CreatedAt string `json:"created_at"`
    Description interface{} `json:"description"`
    Extras struct {
    } `json:"extras"`
    Filesize int `json:"filesize"`
    Filetype string `json:"filetype"`
    Format string `json:"format"`
    ID string `json:"id"`
    LastModified string `json:"last_modified"`
    Latest string `json:"latest"`
    Metrics struct {
    NbHits int `json:"nb_hits"`
    NbUniqVisitors int `json:"nb_uniq_visitors"`
    NbVisits int `json:"nb_visits"`
    Views int `json:"views"`
    } `json:"metrics"`
    Mime string `json:"mime"`
    PreviewURL string `json:"preview_url"`
    Published string `json:"published"`
    Title string `json:"title"`
    Type string `json:"type"`
    URL string `json:"url"`
    } `json:"resources"`
    Slug string `json:"slug"`
    Spatial interface{} `json:"spatial"`
    Tags interface{} `json:"tags"`
    TemporalCoverage interface{} `json:"temporal_coverage"`
    Title string `json:"title"`
    URI string `json:"uri"`
    } `json:"data"`
    Facets struct {
    Format interface{} `json:"format"`
    } `json:"facets"`
    NextPage string `json:"next_page"`
    Page int `json:"page"`
    PageSize int `json:"page_size"`
    PreviousPage interface{} `json:"previous_page"`
    Total int `json:"total"`
    }





    share|improve this answer




























      3














      Once you have data as a map[string]interface{}, you can use type assertions to get to the lower levels of data.



      There's a good explanation here of how to do this at https://blog.golang.org/json-and-go



      Here's an example to get you most of the way:



      https://play.golang.org/p/P8cGP1mTDmD



      package main



      import (
      "encoding/json"
      "fmt"
      "log"
      )

      func main() {
      jsonData := `{
      "string": "string_value",
      "number": 123.45,
      "js_array": ["a", "b", "c"],
      "integer": 678,
      "subtype": {
      "number_array": [1, 2, 3]
      }
      }`

      m := map[string]interface{}{}
      err := json.Unmarshal(byte(jsonData), &m)
      if err != nil {
      log.Fatal(err)
      }

      for key, value := range m {
      switch v := value.(type) {
      case int:
      fmt.Printf("Key: %s, Integer: %dn", key, v)
      case float64:
      fmt.Printf("Key: %s, Float: %vn", key, v)
      case string:
      fmt.Printf("Key: %s, String: %sn", key, v)
      case map[string]interface{}:
      fmt.Printf("Key: %s, Subtype: %+vn", key, v)
      case interface{}:
      //TODO: Read through each item in the interface and work out what type it is.
      fmt.Printf("Key: %s, interface: %vn", key, v)
      default:
      fmt.Printf("Key: %s, unhandled type: %+vn", key, v)
      }
      }
      }


      Alternatively https://mholt.github.io/json-to-go/ does a decent job of turning examples of JSON data into Go structs that can be used for marshalling.



      Putting the example in, I get something that isn't too bad.



      type AutoGenerated struct {
      Data struct {
      Acronym interface{} `json:"acronym"`
      Badges interface{} `json:"badges"`
      CreatedAt string `json:"created_at"`
      Deleted interface{} `json:"deleted"`
      Description string `json:"description"`
      Extras struct {
      } `json:"extras"`
      Frequency string `json:"frequency"`
      FrequencyDate interface{} `json:"frequency_date"`
      ID string `json:"id"`
      LastModified string `json:"last_modified"`
      LastUpdate string `json:"last_update"`
      License string `json:"license"`
      Metrics struct {
      Discussions int `json:"discussions"`
      Followers int `json:"followers"`
      Issues int `json:"issues"`
      NbHits int `json:"nb_hits"`
      NbUniqVisitors int `json:"nb_uniq_visitors"`
      NbVisits int `json:"nb_visits"`
      Reuses int `json:"reuses"`
      Views int `json:"views"`
      } `json:"metrics"`
      Organization struct {
      Acronym string `json:"acronym"`
      Class string `json:"class"`
      ID string `json:"id"`
      Logo string `json:"logo"`
      LogoThumbnail string `json:"logo_thumbnail"`
      Name string `json:"name"`
      Page string `json:"page"`
      Slug string `json:"slug"`
      URI string `json:"uri"`
      } `json:"organization"`
      Owner interface{} `json:"owner"`
      Page string `json:"page"`
      Private bool `json:"private"`
      Resources struct {
      Checksum struct {
      Type string `json:"type"`
      Value string `json:"value"`
      } `json:"checksum"`
      CreatedAt string `json:"created_at"`
      Description interface{} `json:"description"`
      Extras struct {
      } `json:"extras"`
      Filesize int `json:"filesize"`
      Filetype string `json:"filetype"`
      Format string `json:"format"`
      ID string `json:"id"`
      LastModified string `json:"last_modified"`
      Latest string `json:"latest"`
      Metrics struct {
      NbHits int `json:"nb_hits"`
      NbUniqVisitors int `json:"nb_uniq_visitors"`
      NbVisits int `json:"nb_visits"`
      Views int `json:"views"`
      } `json:"metrics"`
      Mime string `json:"mime"`
      PreviewURL string `json:"preview_url"`
      Published string `json:"published"`
      Title string `json:"title"`
      Type string `json:"type"`
      URL string `json:"url"`
      } `json:"resources"`
      Slug string `json:"slug"`
      Spatial interface{} `json:"spatial"`
      Tags interface{} `json:"tags"`
      TemporalCoverage interface{} `json:"temporal_coverage"`
      Title string `json:"title"`
      URI string `json:"uri"`
      } `json:"data"`
      Facets struct {
      Format interface{} `json:"format"`
      } `json:"facets"`
      NextPage string `json:"next_page"`
      Page int `json:"page"`
      PageSize int `json:"page_size"`
      PreviousPage interface{} `json:"previous_page"`
      Total int `json:"total"`
      }





      share|improve this answer


























        3












        3








        3







        Once you have data as a map[string]interface{}, you can use type assertions to get to the lower levels of data.



        There's a good explanation here of how to do this at https://blog.golang.org/json-and-go



        Here's an example to get you most of the way:



        https://play.golang.org/p/P8cGP1mTDmD



        package main



        import (
        "encoding/json"
        "fmt"
        "log"
        )

        func main() {
        jsonData := `{
        "string": "string_value",
        "number": 123.45,
        "js_array": ["a", "b", "c"],
        "integer": 678,
        "subtype": {
        "number_array": [1, 2, 3]
        }
        }`

        m := map[string]interface{}{}
        err := json.Unmarshal(byte(jsonData), &m)
        if err != nil {
        log.Fatal(err)
        }

        for key, value := range m {
        switch v := value.(type) {
        case int:
        fmt.Printf("Key: %s, Integer: %dn", key, v)
        case float64:
        fmt.Printf("Key: %s, Float: %vn", key, v)
        case string:
        fmt.Printf("Key: %s, String: %sn", key, v)
        case map[string]interface{}:
        fmt.Printf("Key: %s, Subtype: %+vn", key, v)
        case interface{}:
        //TODO: Read through each item in the interface and work out what type it is.
        fmt.Printf("Key: %s, interface: %vn", key, v)
        default:
        fmt.Printf("Key: %s, unhandled type: %+vn", key, v)
        }
        }
        }


        Alternatively https://mholt.github.io/json-to-go/ does a decent job of turning examples of JSON data into Go structs that can be used for marshalling.



        Putting the example in, I get something that isn't too bad.



        type AutoGenerated struct {
        Data struct {
        Acronym interface{} `json:"acronym"`
        Badges interface{} `json:"badges"`
        CreatedAt string `json:"created_at"`
        Deleted interface{} `json:"deleted"`
        Description string `json:"description"`
        Extras struct {
        } `json:"extras"`
        Frequency string `json:"frequency"`
        FrequencyDate interface{} `json:"frequency_date"`
        ID string `json:"id"`
        LastModified string `json:"last_modified"`
        LastUpdate string `json:"last_update"`
        License string `json:"license"`
        Metrics struct {
        Discussions int `json:"discussions"`
        Followers int `json:"followers"`
        Issues int `json:"issues"`
        NbHits int `json:"nb_hits"`
        NbUniqVisitors int `json:"nb_uniq_visitors"`
        NbVisits int `json:"nb_visits"`
        Reuses int `json:"reuses"`
        Views int `json:"views"`
        } `json:"metrics"`
        Organization struct {
        Acronym string `json:"acronym"`
        Class string `json:"class"`
        ID string `json:"id"`
        Logo string `json:"logo"`
        LogoThumbnail string `json:"logo_thumbnail"`
        Name string `json:"name"`
        Page string `json:"page"`
        Slug string `json:"slug"`
        URI string `json:"uri"`
        } `json:"organization"`
        Owner interface{} `json:"owner"`
        Page string `json:"page"`
        Private bool `json:"private"`
        Resources struct {
        Checksum struct {
        Type string `json:"type"`
        Value string `json:"value"`
        } `json:"checksum"`
        CreatedAt string `json:"created_at"`
        Description interface{} `json:"description"`
        Extras struct {
        } `json:"extras"`
        Filesize int `json:"filesize"`
        Filetype string `json:"filetype"`
        Format string `json:"format"`
        ID string `json:"id"`
        LastModified string `json:"last_modified"`
        Latest string `json:"latest"`
        Metrics struct {
        NbHits int `json:"nb_hits"`
        NbUniqVisitors int `json:"nb_uniq_visitors"`
        NbVisits int `json:"nb_visits"`
        Views int `json:"views"`
        } `json:"metrics"`
        Mime string `json:"mime"`
        PreviewURL string `json:"preview_url"`
        Published string `json:"published"`
        Title string `json:"title"`
        Type string `json:"type"`
        URL string `json:"url"`
        } `json:"resources"`
        Slug string `json:"slug"`
        Spatial interface{} `json:"spatial"`
        Tags interface{} `json:"tags"`
        TemporalCoverage interface{} `json:"temporal_coverage"`
        Title string `json:"title"`
        URI string `json:"uri"`
        } `json:"data"`
        Facets struct {
        Format interface{} `json:"format"`
        } `json:"facets"`
        NextPage string `json:"next_page"`
        Page int `json:"page"`
        PageSize int `json:"page_size"`
        PreviousPage interface{} `json:"previous_page"`
        Total int `json:"total"`
        }





        share|improve this answer













        Once you have data as a map[string]interface{}, you can use type assertions to get to the lower levels of data.



        There's a good explanation here of how to do this at https://blog.golang.org/json-and-go



        Here's an example to get you most of the way:



        https://play.golang.org/p/P8cGP1mTDmD



        package main



        import (
        "encoding/json"
        "fmt"
        "log"
        )

        func main() {
        jsonData := `{
        "string": "string_value",
        "number": 123.45,
        "js_array": ["a", "b", "c"],
        "integer": 678,
        "subtype": {
        "number_array": [1, 2, 3]
        }
        }`

        m := map[string]interface{}{}
        err := json.Unmarshal(byte(jsonData), &m)
        if err != nil {
        log.Fatal(err)
        }

        for key, value := range m {
        switch v := value.(type) {
        case int:
        fmt.Printf("Key: %s, Integer: %dn", key, v)
        case float64:
        fmt.Printf("Key: %s, Float: %vn", key, v)
        case string:
        fmt.Printf("Key: %s, String: %sn", key, v)
        case map[string]interface{}:
        fmt.Printf("Key: %s, Subtype: %+vn", key, v)
        case interface{}:
        //TODO: Read through each item in the interface and work out what type it is.
        fmt.Printf("Key: %s, interface: %vn", key, v)
        default:
        fmt.Printf("Key: %s, unhandled type: %+vn", key, v)
        }
        }
        }


        Alternatively https://mholt.github.io/json-to-go/ does a decent job of turning examples of JSON data into Go structs that can be used for marshalling.



        Putting the example in, I get something that isn't too bad.



        type AutoGenerated struct {
        Data struct {
        Acronym interface{} `json:"acronym"`
        Badges interface{} `json:"badges"`
        CreatedAt string `json:"created_at"`
        Deleted interface{} `json:"deleted"`
        Description string `json:"description"`
        Extras struct {
        } `json:"extras"`
        Frequency string `json:"frequency"`
        FrequencyDate interface{} `json:"frequency_date"`
        ID string `json:"id"`
        LastModified string `json:"last_modified"`
        LastUpdate string `json:"last_update"`
        License string `json:"license"`
        Metrics struct {
        Discussions int `json:"discussions"`
        Followers int `json:"followers"`
        Issues int `json:"issues"`
        NbHits int `json:"nb_hits"`
        NbUniqVisitors int `json:"nb_uniq_visitors"`
        NbVisits int `json:"nb_visits"`
        Reuses int `json:"reuses"`
        Views int `json:"views"`
        } `json:"metrics"`
        Organization struct {
        Acronym string `json:"acronym"`
        Class string `json:"class"`
        ID string `json:"id"`
        Logo string `json:"logo"`
        LogoThumbnail string `json:"logo_thumbnail"`
        Name string `json:"name"`
        Page string `json:"page"`
        Slug string `json:"slug"`
        URI string `json:"uri"`
        } `json:"organization"`
        Owner interface{} `json:"owner"`
        Page string `json:"page"`
        Private bool `json:"private"`
        Resources struct {
        Checksum struct {
        Type string `json:"type"`
        Value string `json:"value"`
        } `json:"checksum"`
        CreatedAt string `json:"created_at"`
        Description interface{} `json:"description"`
        Extras struct {
        } `json:"extras"`
        Filesize int `json:"filesize"`
        Filetype string `json:"filetype"`
        Format string `json:"format"`
        ID string `json:"id"`
        LastModified string `json:"last_modified"`
        Latest string `json:"latest"`
        Metrics struct {
        NbHits int `json:"nb_hits"`
        NbUniqVisitors int `json:"nb_uniq_visitors"`
        NbVisits int `json:"nb_visits"`
        Views int `json:"views"`
        } `json:"metrics"`
        Mime string `json:"mime"`
        PreviewURL string `json:"preview_url"`
        Published string `json:"published"`
        Title string `json:"title"`
        Type string `json:"type"`
        URL string `json:"url"`
        } `json:"resources"`
        Slug string `json:"slug"`
        Spatial interface{} `json:"spatial"`
        Tags interface{} `json:"tags"`
        TemporalCoverage interface{} `json:"temporal_coverage"`
        Title string `json:"title"`
        URI string `json:"uri"`
        } `json:"data"`
        Facets struct {
        Format interface{} `json:"format"`
        } `json:"facets"`
        NextPage string `json:"next_page"`
        Page int `json:"page"`
        PageSize int `json:"page_size"`
        PreviousPage interface{} `json:"previous_page"`
        Total int `json:"total"`
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 at 19:01









        a-ha-h

        2,9961624




        2,9961624
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997328%2fhow-to-parse-a-nest-json-file-with-unknown-structure-golang%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith