Golang中如何分割字符串并仅获取特定值

Golang中如何分割字符串并仅获取特定值 我需要从下面这个已转换为字符串的JSON中只获取值,即 Basic xxxxxxxxxxxxxxxxxx=

[{"action":"get","node":{"key":"/ridEnvToken","value":"Basic xxxxxxxxxxxxxxxxxx=","modifiedIndex":45,"createdIndex":45}}
3 回复

更多关于Golang中如何分割字符串并仅获取特定值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你好 @mrk

package main

import (
   "fmt"
   "encoding/json"
)

type MYTYPE struct {
   Action string `json:"action"`
   Node   struct {
   	Key           string `json:"key"`
   	Value         string `json:"value"`
   	ModifiedIndex int    `json:"modifiedIndex"`
   	CreatedIndex  int    `json:"createdIndex"`
   } `json:"node"`
}


func main() {
	
   str := `{"action":"get","node":{"key":"/ridEnvToken","value":"Basic xxxxxxxxxxxxxxxxxx=","modifiedIndex":45,"createdIndex":45}}`
   res := MYTYPE {}
   json.Unmarshal([]byte(str), &res)
   fmt.Println(res.Node.Value)
   
}

输出

Basic xxxxxxxxxxxxxxxxxx=

程序已退出。

代码:https://play.golang.org/p/p0XAHa9Ena5

这是你要找的吗?

在Go语言中,你可以使用encoding/json包来解析JSON字符串并提取特定的值。以下是一个示例代码,展示如何从你提供的JSON字符串中提取value字段的值:

package main

import (
	"encoding/json"
	"fmt"
)

// 定义结构体以匹配JSON结构
type Node struct {
	Key           string `json:"key"`
	Value         string `json:"value"`
	ModifiedIndex int    `json:"modifiedIndex"`
	CreatedIndex  int    `json:"createdIndex"`
}

type Item struct {
	Action string `json:"action"`
	Node   Node   `json:"node"`
}

func main() {
	// 输入的JSON字符串
	jsonStr := `[{"action":"get","node":{"key":"/ridEnvToken","value":"Basic xxxxxxxxxxxxxxxxxx=","modifiedIndex":45,"createdIndex":45}}]`

	// 解析JSON到结构体切片
	var items []Item
	err := json.Unmarshal([]byte(jsonStr), &items)
	if err != nil {
		fmt.Printf("解析JSON失败: %v\n", err)
		return
	}

	// 检查切片是否为空并提取值
	if len(items) > 0 {
		value := items[0].Node.Value
		fmt.Printf("提取的值: %s\n", value)
	} else {
		fmt.Println("JSON数组中无元素")
	}
}

运行此代码将输出:

提取的值: Basic xxxxxxxxxxxxxxxxxx=

如果你的JSON结构可能包含多个元素,你可以遍历切片来获取所有值:

for _, item := range items {
    fmt.Printf("值: %s\n", item.Node.Value)
}

这种方法通过定义与JSON结构匹配的Go结构体,并使用json.Unmarshal函数进行解析,确保类型安全且易于维护。

回到顶部