使用Golang的gjson库如何过滤字符串类型的JSON数据

使用Golang的gjson库如何过滤字符串类型的JSON数据

var sms = {id: "test006", collection:"carC",latitude:8.556525,longitude:76.872891}
result:= gjson.Get(sms,“id”).string()

输出:无

以上两行是粗略的代码。

包名:“github.com/tidwall/gjson

4 回复

你的JSON无效。

看起来你使用的库没有传达这些解析错误。

更多关于使用Golang的gjson库如何过滤字符串类型的JSON数据的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


假设“智能引号”是标准的双引号(以后请使用反引号 ` 来包裹代码),乍一看语法似乎是有效的。

{“id”: “278c924b-73a9-427a-b2f2-718f29f3db66”,“collection”:“5f56d384-e1b3-4388-b24a-61c164cd51c3”,“latitude”:11.557536364562386,“longitude”:104.89814115365569}。 你能帮忙检查一下这个JSON吗……?

使用gjson过滤字符串类型JSON数据时,需要确保JSON格式正确且使用正确的访问语法。以下是针对您提供的代码的修正方案:

package main

import (
	"fmt"
	"github.com/tidwall/gjson"
)

func main() {
	// 修正JSON格式:使用双引号包裹键名和字符串值
	sms := `{"id": "test006", "collection": "carC", "latitude": 8.556525, "longitude": 76.872891}`

	// 使用gjson.Get()获取字段值,注意方法名是String()而非string()
	result := gjson.Get(sms, "id").String()
	fmt.Println(result) // 输出:test006

	// 过滤其他字符串字段示例
	collection := gjson.Get(sms, "collection").String()
	fmt.Println(collection) // 输出:carC

	// 检查字段是否存在且为字符串类型
	if gjson.Get(sms, "id").Exists() && gjson.Get(sms, "id").Type == gjson.String {
		fmt.Println("字段存在且为字符串类型")
	}

	// 批量获取多个字符串字段
	ids := gjson.GetMany(sms, "id", "collection")
	for _, res := range ids {
		fmt.Println(res.String())
	}
}

关键修正点:

  1. JSON必须使用双引号包裹键名和字符串值
  2. 使用.String()方法(首字母大写)获取字符串结果
  3. 原始代码中的{id: "test006",...}格式不符合标准JSON规范

如果输入数据格式无法更改,可先进行预处理:

// 处理非标准JSON格式
raw := `{id: "test006", collection:"carC",latitude:8.556525,longitude:76.872891}`
// 添加双引号到键名(简单示例,实际可能需要更复杂的解析)
processed := `{"id": "test006", "collection": "carC", "latitude": 8.556525, "longitude": 76.872891}`
result := gjson.Get(processed, "id").String()
回到顶部