如何在 Go 中解析 JSON 数组 [英] How to parse JSON array in Go
本文介绍了如何在 Go 中解析 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 json 包在 Go 中解析字符串(即数组)?
How to parse a string (which is an array) in Go using json package?
type JsonType struct{
Array []string
}
func main(){
dataJson = `["1","2","3"]`
arr := JsonType{}
unmarshaled := json.Unmarshal([]byte(dataJson), &arr.Array)
log.Printf("Unmarshaled: %v", unmarshaled)
}
推荐答案
返回值<Unmarshal
的/a> 是一个 error,这是您正在打印的内容:
The return value of Unmarshal
is an error, and this is what you are printing out:
// Return value type of Unmarshal is error.
err := json.Unmarshal([]byte(dataJson), &arr)
你也可以去掉 JsonType
并且只使用一个切片:
You can get rid of the JsonType
as well and just use a slice:
package main
import (
"encoding/json"
"log"
)
func main() {
dataJson := `["1","2","3"]`
var arr []string
_ = json.Unmarshal([]byte(dataJson), &arr)
log.Printf("Unmarshaled: %v", arr)
}
// prints out:
// 2009/11/10 23:00:00 Unmarshaled: [1 2 3]
播放代码:https://play.golang.org/p/GNWlylavam
背景:传入指针允许 Unmarshal
减少(或完全摆脱)内存分配.此外,在处理上下文中,调用者可能会重复使用相同的值 - 也可以节省分配.
Background: Passing in a pointer allows Unmarshal
to reduce (or get entirely rid of) memory allocations. Also, in a processing context, the caller may reuse the same value to repeatedly - saving allocations as well.
这篇关于如何在 Go 中解析 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文