首页 > 其他分享 >Go - The map[string]interface{} map

Go - The map[string]interface{} map

时间:2024-06-11 19:32:28浏览次数:13  
标签:map string fmt Println JSON Go interface

Remember that the biggest advantage you get from using a map[string]interface{} map, or any map that stores an interface{} value in general, is that you still have your data in its original state and data type.

Nowadays, web services work by exchanging JSON records. If you get a JSON record in an anticipated format, then you can process it as expected and everything will be fine. However, there are times when you might get an erroneous record or a record in an unsupported JSON format. In these cases, using map[string]interface{} for storing these unknown JSON records (arbitrary data) is a good choice because map[string]interface{} is good at storing JSON records of unknown types.

 

package main

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

var JSONrecord = `{
    "Flag": true,
    "Array": ["a","b","c"],
    "Entity": {
        "a1": "b1",
        "a2": "b2",
        "Value": -456,
        "Null": null
    },
    "Message": "Hello Go!"
}`

func typeSwitch(m map[string]interface{}) {
    for k, v := range m {
        switch c := v.(type) {
        case string:
            fmt.Println("Is a string!", k, c)
        case float64:
            fmt.Println("Is a float64!", k, c)
        case bool:
            fmt.Println("Is a Boolean!", k, c)
        case map[string]interface{}:
            fmt.Println("Is a map!", k, c)
            typeSwitch(v.(map[string]interface{}))
        default:
            fmt.Printf("...Is %v: %T!\n", k, c)
        }
    }
}

func exploreMap(m map[string]interface{}) {
    for k, v := range m {
        embMap, ok := v.(map[string]interface{})
        // If it is a map, explore deeper
        if ok {
            fmt.Printf("{\"%v\": \n", k)
            exploreMap(embMap)
            fmt.Printf("}\n")
        } else {
            fmt.Printf("%v: %v\n", k, v)
        }
    }
}

func main() {
    if len(os.Args) == 1 {
        fmt.Println("*** Using default JSON record.")
    } else {
        JSONrecord = os.Args[1]
    }
    JSONMap := make(map[string]interface{})
    err := json.Unmarshal([]byte(JSONrecord), &JSONMap)
    if err != nil {
        fmt.Println(err)
        return
    }
    exploreMap(JSONMap)
    fmt.Println("------------------------------------------------")
    typeSwitch(JSONMap)
}

 

标签:map,string,fmt,Println,JSON,Go,interface
From: https://www.cnblogs.com/zhangzhihui/p/18242600

相关文章

  • 如何利用 Google 搜索结果页来引导?
    在数据驱动的决策世界中,获取准确而全面的信息至关重要。Google搜索结果抓取是一种强大的技术,可以让企业、调查人员和研究人员从搜索引擎结果中提取可靠的数据。本综合指南将深入研究Google搜索结果的最佳实践、工具和道德考量,以确定能够有效利用这一技术。了解Google搜索......
  • Django学习项目-learning log报错合集(2)
    样式篇stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css:1  Failedtoloadresource:net::ERR_CONNECTION_TIMED_OUTdjango-bootstrap3样式无效按这篇文章进行修改......
  • Go变量作用域精讲及代码实战
    关注作者,复旦AI博士,分享AI领域与云服务领域全维度开发技术。拥有10+年互联网服务架构、AI产品研发经验、团队管理经验,同济本复旦硕博,复旦机器人智能实验室成员,国家级大学生赛事评审专家,发表多篇SCI核心期刊学术论文,阿里云认证的资深架构师,项目管理专业人士,上亿营收AI产品研发负责......
  • Dragon Boat Festival
    TheDragonBoatFestival,alsoknownasDuanwuJie,isatimeofvibrantculturalcelebration,steepedinhistoryandrichwithtraditionsthatbindcommunitiestogether.Asthefestivalapproaches,ourcommunityisabuzzwithexcitementandpreparations......
  • Dragon Boat Festival
    Thefestival,whichcommemoratestheancientChinesepoetQuYuan,isatimeforfamilyreunions,dragonboatraces,andtheconsumptionoftraditionalfoodslikezongzi.Butthisyear,becauseofstudyinginotherplaces,Ionlyatezongzi,whichisthef......
  • The Dragon Boat Festival
    TheDuanwuFestivalinChina,alsocalledDragonBoatFestival,iscelebratedonday5ofthefifthmontheveryyearaccordingtotheChineselunarcalendar.EveryyearontheDragonBoatFestival,wegetupearlyandstartpreparingzongzi.We'llad......
  • Dragon Boat Festival
    FestivalPreparationDuringtheDragonBoatFestival,ourfamily'spreparationsalwaysexudeastrongsenseofritual.Wehangwormwoodandcalamusathome,intendingtodriveawayevilspiritsandprayforthewell-beingofourfamily.Thistraditio......
  • Dragon Boat Festival
    ItwasbelievedthatQuYuancommittedsuicideintheMiluoRiver.DuanwuFestival,alsonamedtheDragonBoatFestival,atraditioninmemoryofthegreatpatrioticpoetQuYuan,fallsonthefifthdayofthefifthmonthoftheChinesecalendar.Whenthe......
  • 飞书golang 发送机器人结构定义
    飞书golang发送机器人结构定义在Golang中,可以定义一个结构体来表示飞书(Feishu)机器人的数据。以下是一个简单的示例,展示了如何定义用于发送消息到飞书机器人的结构体:  packagemain import("bytes""encoding/json""fmt""net/http") //FeishuRobotPayl......
  • Dragon Boat Festival
    WhenIrealizedthatDragonBoatFestivalwascoming,myheartwasfullofhappiness.ThisDragonBoatFestivalisalsospecialforme.Let'sreviewthehistoryoftheDragonBoatFestival.TheDragonBoatFestival,alsoknownasDuanwuFestival,i......