Go语言学习: 嵌套json/gjson库

关于嵌套json
更新于: 2024-11-11 03:29:29

main.go

package main

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

func main() {
	// 定义嵌套的JSON数据结构
	data := map[string]interface{}{
		"user": map[string]interface{}{
			"name": "John Doe",
			"age":  30,
		},
		"status": "active",
	}

	// 将数据编码为JSON格式
	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Fatal("Error encoding JSON:", err)
	}

	// 打印编码后的JSON
	fmt.Println("JSON Data: ", string(jsonData))
}

gjson 库

package main

import (
	"fmt"

	"github.com/tidwall/gjson"
)

func main() {
	// 假设 resultJSON 是 JSON 格式的字符串
	resultJSON := `{"age": 25, "name": "Alice", "address": {"city": "Wonderland"}}`

	// 直接通过路径获取嵌套字段
	age := gjson.Get(resultJSON, "age")
	name := gjson.Get(resultJSON, "name")
	city := gjson.Get(resultJSON, "address.city")

	fmt.Printf("Age: %v\n", age)
	fmt.Printf("Name: %v\n", name)
	fmt.Printf("City: %v\n", city)
}