golang 解析json 動態數組

#cat file
{
   "Bangalore_City": "35_Temperature",
   "NewYork_City": "31_Temperature",
   "Copenhagen_City": "29_Temperature"
}
#cat   json.go
package main

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

var m map[string]string

func ReadFileAll(filePath string) ([]byte, error) {
    f, err := os.Open(filePath)
    if err != nil {
        return nil, err
    }
    return ioutil.ReadAll(f)
}

func UnmarshalFile() (err error) {
    var bytecodes []byte

    m = map[string]string{}
    bytecodes, err = ReadFileAll("file")
    if err != nil {
        return err
    }

    err = json.Unmarshal(bytecodes, &m)
    if err != nil {
        fmt.Printf("unmarshal failed\n")
    }

    for k, v := range m {
        fmt.Println(k, v)
    }
    return err
}

func main() {
    UnmarshalFile()
}
#go run json.go
Bangalore_City 35_Temperature
NewYork_City 31_Temperature
Copenhagen_City 29_Temperature
相關文章
相關標籤/搜索