如何在 Go 中导航具有未知结构的嵌套 json?

Ema*_*o78 1 json dictionary interface go

我正在尝试从 Go Lang 中的深层嵌套 json 数据中解析并获取选定的数据。我在浏览结构和访问数据时遇到问题。数据太深太复杂,无法用 Go 中的先验已知结构进行解析。这是文件的 URL: - https://www.data.gouv.fr/api/1/datasets/?format=csv&page=0&page_size=20

我使用地图接口并使用 json 字符串进行了一些解析:

resultdata := map[string]interface {}

json.Unmarshal([]byte(inputbytestring), &resultdata) //Inputstring is the string containing the JSON data of the above URL
Run Code Online (Sandbox Code Playgroud)

问题:

  • 如何将结果数据转换为(字符串)地图,以便我可以使用可用于地图的方法?
  • JSON 数据是嵌套的并且有多个级别。如何访问较低级别的 JSON 字段?是否可以递归地解组数据?

a-h*_*a-h 7

一旦您获得了 a 数据map[string]interface{},您就可以使用类型断言来获取较低级别的数据。

https://blog.golang.org/json-and-go有一个关于如何执行此操作的很好的解释

下面是一个可以帮助您了解大部分内容的示例:

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

包主

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: %d\n", key, v)
        case float64:
            fmt.Printf("Key: %s, Float: %v\n", key, v)
        case string:
            fmt.Printf("Key: %s, String: %s\n", key, v)
        case map[string]interface{}:
            fmt.Printf("Key: %s, Subtype: %+v\n", key, v)
        case []interface{}:
            //TODO: Read through each item in the interface and work out what type it is.
            fmt.Printf("Key: %s, []interface: %v\n", key, v)
        default:
            fmt.Printf("Key: %s, unhandled type: %+v\n", key, v)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,https://mholt.github.io/json-to-go/在将 JSON 数据示例转换为可用于编组的 Go 结构方面做得不错。

把这个例子放进去,我得到的东西还不错。

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"`
}
Run Code Online (Sandbox Code Playgroud)