首页 文章

如何在没有定义Golang结构的情况下读取json的“接口”映射?

提问于
浏览
-1

this tutorial之后我试图在Golang中读取一个json文件 . 它说有两种方法可以做到这一点:

  • 使用一组预定义的结构解组JSON

  • 或使用map [string] interface {}解组JSON

由于我可能有很多不同的json格式,我更喜欢在运行中解释它 . 所以我现在有以下代码:

package main

import (
    "fmt"
    "os"
    "io/ioutil"
    "encoding/json"
)

func main() {
    // Open our jsonFile
    jsonFile, err := os.Open("users.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Successfully Opened users.json")
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()

    byteValue, _ := ioutil.ReadAll(jsonFile)

    var result map[string]interface{}
    json.Unmarshal([]byte(byteValue), &result)

    fmt.Println(result["users"])
    fmt.Printf("%T\n", result["users"])
}

打印出:

Successfully Opened users.json
[map[type:Reader age:23 social:map[facebook:https://facebook.com twitter:https://twitter.com] name:Elliot] map[name:Fraser type:Author age:17 social:map[facebook:https://facebook.com twitter:https://twitter.com]]]
[]interface {}

此时我不明白如何读取第一个用户的年龄(23) . 我尝试了一些变化:

fmt.Println(result["users"][0])
fmt.Println(result["users"][0].age)

但显然, type interface {} does not support indexing .

有没有一种方法可以在不定义结构的情况下访问json中的项目?

1 回答

  • 1

    可能你想要的

    fmt.Println(result["users"].(map[string]interface{})["age"])
    

    要么

    fmt.Println(result[0].(map[string]interface{})["age"])
    

    由于JSON是映射的映射,叶节点的类型是接口{},因此必须转换为map [string] interface {}才能查找键

    定义结构更容易 . 我这样做的最重要的提示是使用一个将JSON转换为Go结构定义的网站,如Json-To-Go

相关问题