golang读取json文件的几种方式

store.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[
  {
    "id": 1,
    "name": "川菜馆",
    "user_id": 12345,
    "cover_price": 200,
    "menus": [
      {
        "id": 1,
        "name": "干煸土豆丝",
        "price": 1800,
        "type": 1
      },
      {
        "id": 2,
        "name": "青椒肉丝",
        "price": 1600,
        "type": 1
      },
      {
        "id": 3,
        "name": "清炒莴笋",
        "price": 1300,
        "type": 1
      }
    ]
  }
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main

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

//定义配置文件解析后的结构
type Menu struct {
	ID       int8   `sql:"id" json:"id,omitempty"` //菜单编号
	Name     string `sql:"name" json:"name,omitempty"` //菜单名称
	Price    int8   `sql:"price" json:"price,omitempty"` //菜单价格
	MenuType int    `sql:"type" json:"type,omitempty"` //菜单类型 1.小炒 2.火锅 3.凉菜 4.汤
}

type Store struct {
	Id   int8 `sql:"id" json:"id,omitempty"` //店铺编号
	UserId int8 `sql:"user_id" json:"user_id,omitempty"` //用户编号
	Name string `sql:"name" json:"name,omitempty"`//店铺名称
	CoverPrice int  `sql:"cover_price" json:"cover_price,omitempty"`//店铺人均服务费或者每人米饭钱
	Menus [] Menu `sql:"menus" json:"menus,omitempty"`
}

func init() {
	flag.Parse()
}

var person = flag.Int("person", 5, "吃饭的人数")
var price = flag.Int("price", 1500, "期望人均价格")
var num = flag.Int("num", 5, "期望菜数量")
var store = flag.Int("store", 0, "期望去的菜馆")



func main() {
	JsonParse := NewJsonObject()
	v := []Store{}
	//下面使用的是相对路径,config.json文件和main.go文件处于同一目录下
	JsonParse.Load("./stores.json", &v)
	fmt.Println("期望去的菜馆: ", *store)
	fmt.Println("吃饭的人数: ", *person)
	fmt.Println("期望总价格: ", *price)
	fmt.Println("期望菜数量: ", *num)
	fmt.Println(v[*store])
	totalFee := (*person) * (*price)
	dishPrice := (*person) * (*price) - (*person)* (v[*store].CoverPrice)

	fmt.Println("期望总费用: ", totalFee)
	fmt.Println("期望吃菜费用: ", dishPrice)
	//menus := v[*store].Menus todo

}

type JsonObject struct {
}

func NewJsonObject() *JsonObject {
	return &JsonObject{}
}

func (jst *JsonObject) Load(filename string, v interface{}) {
	//ReadFile函数会读取文件的全部内容,并将结果以[]byte类型返回
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}
	//读取的数据为json格式,需要进行解码
	err = json.Unmarshal(data, v)
	if err != nil {
		return
	}
}