json - 当结构未知时遍历 JSON 响应

标签 json go struct iteration decode

我有一个 http 服务器,我想处理 JSON 响应以覆盖 JSON 文件,我希望能够解析任何数量的数据和结构。

所以我的 JSON 数据可能如下所示:

{
  "property1": "value",
  "properties": {
    "property1": 1,
    "property2": "value"
  }
}

或者它可以是这样的:

{"property": "value"}

我想遍历每个属性,如果它已经存在于 JSON 文件中,则覆盖它的值,否则将其附加到 JSON 文件。

我试过使用 map 但它似乎不支持索引。我可以使用 map["property"] 搜索特定属性,但我的想法是我还不知道任何 JSON 数据。

我如何(在不知道结构的情况下)遍历每个属性并打印其属性名称和值?

最佳答案

How can I (without knowing the struct) iterate through each property and print both its property name and value?

这是一个基本函数,它通过解析的 json 数据结构递归并打印键/值。它没有经过优化,并且可能无法解决所有边缘情况(例如数组中的数组),但您明白了。 Playground .

给定一个像 {"someNumerical":42.42,"stringsInAnArray":["a","b"]} 这样的对象,输出如下:

object {
key: someNumerical value: 42.42
key: stringsInAnArray value: array [
value: a
value: b
]
value: [a b]
}

代码:

func RecurseJsonMap(dat map[string]interface{}) {
    fmt.Println("object {")   
    for key, value := range dat {
        fmt.Print("key: " + key + " ")        
    // print array properties
    arr, ok := value.([]interface{})
    if ok {
        fmt.Println("value: array [") 
        for _, arrVal := range arr {
            // recurse subobjects in the array
            subobj, ok := arrVal.(map[string]interface{})
            if ok {
                RecurseJsonMap(subobj)
            } else {            
                // print other values
                fmt.Printf("value: %+v\n", arrVal)        
            }   
        }
        fmt.Println("]")    
    }

    // recurse subobjects
    subobj, ok := value.(map[string]interface{})
    if ok {
        RecurseJsonMap(subobj)
    } else {            
            // print other values
            fmt.Printf("value: %+v\n" ,value)        
        } 
    }
    fmt.Println("}")   
}

func main() {
    // some random json object in a string
    byt := []byte(`{"someNumerical":42.42,"stringsInAnArray":["a","b"]}`)

    // we are parsing it in a generic fashion
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    RecurseJsonMap(dat)
}

关于json - 当结构未知时遍历 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48797682/

相关文章:

javascript - Bootstrap Accordion 。保留多个面板的页面加载状态

javascript - 有效地重命名/重新映射对象数组中的 javascript/json 对象键

Javascript,未捕获的类型错误 : Cannot read property "cells" of undefined

go - 如何在 Google Cloud Functions with Go 中使用 vendor 的本地存储库

google-app-engine - Google 应用引擎 + Go + 数据存储 + 添加/更新/删除记录

c - 指向结构指针内字符串中的字符

json - 在 Swift 4 中序列化 JSON - 确定数据类型的问题

struct - 递归打印 struct in `fmt::Display`

python - "Struct arrays"

arrays - 如何在 golang 中将字节数组打印为二进制?