登录
首页 >  Golang >  Go问答

解析 JSON 数据并以类似 Python 字典的形式访问值

来源:stackoverflow

时间:2024-02-17 17:21:11 475浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《解析 JSON 数据并以类似 Python 字典的形式访问值》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("https://s3.us-west-2.amazonaws.com/cloudformation-templates-us-west-2/AutoScalingMultiAZWithNotifications.template")

    if err !=nil {
        fmt.Println(err)

    }

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        fmt.Println(err)
    }

    v := make(map[string] interface{})

    json.Unmarshal(body, &v)

    fmt.Println(v)
}

解决方案


package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("https://s3.us-west-2.amazonaws.com/cloudformation-templates-us-west-2/AutoScalingMultiAZWithNotifications.template")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    v := make(map[string]interface{})
    if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
        panic(err)
    }

    // index into map v and type-assert the value
    if Parameters, ok := v["Parameters"].(map[string]interface{}); ok {
        // index into Parameters and if found, print
        if VpcId, ok := Parameters["VpcId"]; ok {
            fmt.Println(VpcId)
        }
    }

}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>