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
posted @ 2019-06-25 18:12  苏小北1024  阅读(1907)  评论(0编辑  收藏  举报