Go-json解码到接口及根据键获取值

Go-json解码到接口及根据键获取值

package main

import (
	"encoding/json"
	"fmt"
	"github.com/bitly/go-simplejson"
)

type JsonServer struct {
	ServerName string
	ServerIP   string
}

type JsonServers struct {
	Servers []JsonServer
}

func main() {
	var s JsonServers
	str := `{"servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
	json.Unmarshal([]byte(str), &s)

	fmt.Println(s) //{[{Shanghai_VPN 127.0.0.1} {Beijing_VPN 127.0.0.2}]}

	b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
	var f interface{}
	json.Unmarshal(b, &f)
	fmt.Printf("%+v\n", f) // map[Name:Wednesday Age:6 Parents:[Gomez Morticia]]

	m := f.(map[string]interface{})
	for k, v := range m {
		switch vv := v.(type) {
		case string:
			fmt.Println(k, "is string", vv) //Name is string Wednesday
		case int:
			fmt.Println(k, "is int", vv)
		case float64:
			fmt.Println(k, "is float64", vv) //Age is float64 6
		case []interface{}:
			fmt.Println(k, "is an array:") //Parents is an array:
			//0 Gomez
			//1 Morticia
			for i, u := range vv {
				fmt.Println(i, u)
			}
		default:
			fmt.Println(k, "is of a type I don't know how to handle")
		}
	}

	/**
	如您所见,我们现在可以通过interface{}解析未知格式的JSON并键入断言。
	以上示例是官方解决方案,但类型断言并不总是方便。
	因此,我推荐一个名为simplejson的开源项目,由bitly创建和维护。
	以下是如何使用此项目处理未知格式的JSON的示例:
	go get ithub.com/bitly/go-simplejson
	*/
        // 根据键获取值
	js, err := simplejson.NewJson([]byte(`{
    "test": {
        "array": [1, "2", 3],
        "int": 10,
        "float": 5.150,
        "bignum": 9223372036854775807,
        "string": "simplejson",
        "bool": true
    }
}`))
	if err != nil {
		fmt.Println("err:", err)
	}

	arr, _ := js.Get("test").Get("array").Array() //arr: [1 2 3]
	fmt.Println("arr:", arr)
	i, _ := js.Get("test").Get("int").Int() //i: 10
	fmt.Println("i:", i)
	ms := js.Get("test").Get("string").MustString() //ms: simplejson
	fmt.Println("ms:", ms)
}

json解码到接口

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonBuf := `
	{
		"company": "itcast",
		"subjects": [
			"Go",
			"C++",
			"Python",
			"Test"
		],
		"isok": true,
		"price": 666.666
	}
	`
	//创建一个map
	m := make(map[string]interface{}, 4)
	err := json.Unmarshal([]byte(jsonBuf), &m)
	if err != nil {
		fmt.Println("err=", err)
		return
	}
	fmt.Println("m=", m)     //m= map[company:itcast subjects:[Go C++ Python Test] isok:true price:666.666]
	fmt.Printf("m=%+v\n", m) //m=map[isok:true price:666.666 company:itcast subjects:[Go C++ Python Test]]

	var s string
	s = m["company"].(string)
	fmt.Println("s= ", s) //s=  itcast

	var s1 bool
	s1 = m["isok"].(bool)
	fmt.Println("s1= ", s1) //s1=  true

	var s2 float64
	s2 = m["price"].(float64)
	fmt.Println("s2= ", s2) //s2=  666.666

	var str string
	//类型断言
	for key, value := range m {
		// fmt.Printf("%v===>%v\n", key, value)
		switch data := value.(type) {
		case string:
			str = data
			fmt.Printf("map[%s]的值类型为string,内容为%s\n", key, str)
		case bool:
			fmt.Printf("map[%s]的值类型为bool,内容为%v\n", key, data)
		case float64:
			fmt.Printf("map[%s]的值类型为float64,内容为%v\n", key, data)
		case []string:
			fmt.Printf("map[%s]的值类型为[]stiring1,内容为%v\n", key, data)
		case []interface{}:
			fmt.Printf("map[%s]的值类型为[]stiring2,内容为%v\n", key, data)
		}
		/*
			map[company]的值类型为string,内容为itcast
			map[subjects]的值类型为[]stiring2,内容为[Go C++ Python Test]
			map[isok]的值类型为bool,内容为true
			map[price]的值类型为float64,内容为666.666
		*/
	}
}

posted @ 2019-07-18 22:40  大西瓜Paul  阅读(1126)  评论(0编辑  收藏  举报
/*增加返回顶部按钮*/ 返回顶部 /*给标题增加蓝色背景长条*/