如何在GO中浏览带有未知结构的嵌套JSON? 我正在尝试解析并从Go Lang中的深嵌套JSON数据中获取所选数据。我遇到了通过结构导航并访问数据的问题。数据太深而复杂,无法是

问题描述 投票:0回答:3

resultdata := map[string]interface {} json.Unmarshal([]byte(inputbytestring), &resultdata) //Inputstring is the string containing the JSON data of the above URL 问题:

如何将Resultdata变成(字符串的)地图,因此我可以使用可用于地图的方法?

JSON数据已嵌套并具有多个级别。如何访问较低级别的JSON字段?是否可以递归地删除数据?

  • 您将数据作为
  • map[string]interface{}
,您可以使用类型的断言来达到较低的数据级别。
json dictionary go interface
3个回答
7
投票
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) } } }

thershinehttps://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"` }
    

如果您希望快速用途的嵌套数据对内联解码,请遵循以下方法:

myJsonData := `{ "code": "string_code", "data": { "id": 123, "user": { "username": "my_username", "age": 30, "posts": [ "post1", "post2"] } } }`

Llet说您有上述嵌套且未知的数据想要阅读和解析,首先将其读为
JSON

3
投票

map[string]interface{}

现在您想访问
m := map[string]interface{}{} err := json.Unmarshal([]byte(myJsonData), &m) if err != nil { log.Fatal(err) }

code
在嵌套json的嵌套块:

    fmt.Println(m["code"])

在JSON的嵌套

id
嵌套块中:

data

在JSON的嵌套

    fmt.Println(m["data"].(map[string]interface{})["id"].(float64))
嵌套块中:
username

在JSON的嵌套
second level

嵌套块中:

user
求plays在
Playground中查看示例


通过GO中的无型JSON进行措施可能具有挑战性,因为我们必须处理从

    fmt.Println(m["data"].(map[string]interface{})["user"].(map[string]interface{})["username"].(string))
到实际基础值类型(
age
second level

user
fmt.Println(m["data"].(map[string]interface{})["user"].(map[string]interface{})["age"].(float64))

post1
third level
)的铸造值。 您可以使用库来帮助您完成诸如
jsonnav
的任务。

考虑以下JSON:
posts

然后您可以访问深嵌套的属性,而不必担心 fmt.Println(m["data"].(map[string]interface{})["user"].(map[string]interface{})["posts"].([]interface{})[0].(string))

检查或类型铸造:

0
投票
any

disclaimer:我是
jsonnavpackage
.

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.