英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论