将 JSON 数组转换为切片。

huangapple go评论66阅读模式
英文:

gjson: cast json array as a slice

问题

使用gjson包,将gjson.Result对象转换为字符串很简单,可以使用j.Get("str").String(),但我无法弄清如何将对象转换为字符串切片。例如:

package main

import (
	"fmt"

	"github.com/tidwall/gjson"
)

func main() {
	j := `{"array": ["a","b","c"]}`
	gj := gjson.Parse(j).Get("array").Array()
	for k, v := range gj {
		fmt.Println(k, v.String())
	}
}

这样做会失败,因为Value()将数组转换为无法进行迭代的接口类型。

英文:

Using the gjson package, casting gjson.Result objects to a string is simple j.Get("str").String() but I can't figure out how to cast an object to a string slice. E.g.:

package main

import (
	"fmt"

	"github.com/tidwall/gjson"
)

func main() {
	j := `{"array": ["a","b","c"]}`
	gj := gjson.Parse(j).Get("array").Value()
	for k, v := range gj {
		fmt.Println(k, v)
	}
}

This fails as Value() casts the array as an Interface which cannot be ranged over.

答案1

得分: 3

从API文档中可以看出,Parse().Get()的结果是一个Result()类型。该包支持多种方便的函数来处理这种类型。例如,你只需要使用Array()方法。

func main() {
    j := `{"array": ["a","b","c"]}`
    gj := gjson.Parse(j).Get("array").Array()
    for k, v := range gj {
        fmt.Println(k, v)
    }
}

请注意,该包适用于特定于JSON而不是Go的类型。

在JSON上下文中,返回的值是一个数组类型。因此,如果你需要一个[]string类型,可以使用Result.Str属性自己创建。

func main() {
    j := `{"array": ["a","b","c"]}`
    var result []string
    gj := gjson.Parse(j).Get("array").Array()
    for _, v := range gj {
        result = append(result, v.Str)
    }
    
}
英文:

From the API docs, the result of Parse().Get() is a Result() type. The package supports a variety of handy functions that work on the type. e.g. you just need the Array() method

func main() {
    j := `{"array": ["a","b","c"]}`
    gj := gjson.Parse(j).Get("array").Array()
    for k, v := range gj {
        fmt.Println(k, v)
    }
}

Note that, the package works with the types specific to JSON and not Go in general.

In JSON context the returned value is an array type. So if you were to need a []string type, create your own, using the Result.Str attribute

func main() {
    j := `{"array": ["a","b","c"]}`
    var result []string
    gj := gjson.Parse(j).Get("array").Array()
    for _, v := range gj {
        result = append(result, v.Str)
    }
    
}

huangapple
  • 本文由 发表于 2021年8月25日 18:51:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/68921506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定