• 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
    ", 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
    ", 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
    ", key, value)
    		switch data := value.(type) {
    		case string:
    			str = data
    			fmt.Printf("map[%s]的值类型为string,内容为%s
    ", key, str)
    		case bool:
    			fmt.Printf("map[%s]的值类型为bool,内容为%v
    ", key, data)
    		case float64:
    			fmt.Printf("map[%s]的值类型为float64,内容为%v
    ", key, data)
    		case []string:
    			fmt.Printf("map[%s]的值类型为[]stiring1,内容为%v
    ", key, data)
    		case []interface{}:
    			fmt.Printf("map[%s]的值类型为[]stiring2,内容为%v
    ", key, data)
    		}
    		/*
    			map[company]的值类型为string,内容为itcast
    			map[subjects]的值类型为[]stiring2,内容为[Go C++ Python Test]
    			map[isok]的值类型为bool,内容为true
    			map[price]的值类型为float64,内容为666.666
    		*/
    	}
    }
    
    
  • 相关阅读:
    Vue学习笔记【28】——Vue路由(使用 children 属性实现路由嵌套)
    Vue学习笔记【27】——Vue路由(设置路由)
    Vue学习笔记【26】——Vue路由(什么是路由)
    Vue学习笔记【25】——Vue组件(组件间传值)
    Vue学习笔记【24】——Vue组件(组件切换)
    Vue学习笔记【23】——Vue组件(组件的定义)
    ga统计
    token验证机制
    网站发布(项目上线流程)
    使用CSS将图片转换成黑白(灰色、置灰) & 毛玻璃效果
  • 原文地址:https://www.cnblogs.com/Paul-watermelon/p/11210526.html
Copyright © 2020-2023  润新知