登录
原创

golang深度搜索多层级json数据

发布于 2022-10-25 阅读 1006
  • Go
  • 深度学习
原创
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func main() {
	b := []byte(`{
	"company": "itcast",
	"subjects": [
		"Go",
		"C++",
		"Python",
		"Test"
	],
	"isok": true,
	"int": 12,
	"int1": 2323232323,
	"data": {
		"name": "silk",
		"age": 12,
		"student": {
			"name": "silk",
			"age": 12,
			"hello": {
				"score": 100,
				"height": 12,
				"nick": {
					"na": 1,
					"xx": [{
						"a": 1
					}, {
						"b": 2
					}]
				}
			}
		}
	},
	"price": 666.666
}`)

	var t interface{}
	err := json.Unmarshal(b, &t)
	if err != nil {
		fmt.Println("json err:", err)
		return
	}

	//使用断言判断类型
	m := t.(map[string]interface{})
	fmt.Println(m)
	x := "data.student.hello.nick.xx"
	result := deepSearch(m, x)
	fmt.Println()
	fmt.Println()
	fmt.Println()
	fmt.Println()
	fmt.Println(result)

}
func deepSearch(m map[string]interface{}, key string) (result interface{}) {
	defer func() {
		if recover() != nil {
			result = nil
			return
		}
	}()
	if !strings.Contains(key, ".") {
		return m[key]
	}
	prefix := key[:strings.Index(key, ".")]
	suffix := key[strings.Index(key, ".")+1:]
	for k, v := range m {
		if k == prefix {
			if strings.Contains(suffix, ".") {
				return deepSearch(v.(map[string]interface{}), suffix)
			} else {
				result = v.(map[string]interface{})[suffix]
				return
			}
		}
	}
	return
}

评论区

眉上的汗水,眉下的泪水,你总要选择一样

0

0

0

举报