在 Golang 中解析 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38867692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:32:34  来源:igfitidea点击:

Parse JSON array in Golang

arraysjsongoslice

提问by kingSlayer

Simple question: how to parse a string (which is an array) in Go using json package?

简单的问题:如何使用 json 包在 Go 中解析字符串(这是一个数组)?

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)
}

回答by miku

The return valueof Unmarshalis an err, and this is what you are printing out:

返回值Unmarshal是错了,这是要打印出来的内容:

// Return value type of Unmarshal is error.
err := json.Unmarshal([]byte(dataJson), &arr)

You can get rid of the JsonTypeas well and just use a slice:

你也可以去掉 ,JsonType只使用一个切片:

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]

Code on play: https://play.golang.org/p/GNWlylavam

游戏代码:https: //play.golang.org/p/GNWlylavam

回答by icza

Note:This answer was written before the question was edited. In the original question&arrwas passed to json.Unmarshal():

注意:这个答案是在编辑问题之前写的。在原来的问题&arr被传递给json.Unmarshal()

unmarshaled := json.Unmarshal([]byte(dataJson), &arr)


You pass the address of arrto json.Unmarshal()to unmarshal a JSON array, but arris not an array (or slice), it is a struct value.

您传递arrto的地址json.Unmarshal()以解组 JSON 数组,但arr它不是数组(或切片),而是一个结构值。

Arrays can be unmarshaled into Go arrays or slices. So pass arr.Array:

数组可以解组为 Go 数组或切片。所以通过arr.Array

dataJson := `["1","2","3"]`
arr := JsonType{}
err := json.Unmarshal([]byte(dataJson), &arr.Array)
log.Printf("Unmarshaled: %v, error: %v", arr.Array, err)

Output (try it on the Go Playground):

输出(在Go Playground上试试):

2009/11/10 23:00:00 Unmarshaled: [1 2 3], error: <nil>

Of course you don't even need the JsonTypewrapper, just use a simple []stringslice:

当然,您甚至不需要JsonType包装器,只需使用一个简单的[]string切片:

dataJson := `["1","2","3"]`
var s []string
err := json.Unmarshal([]byte(dataJson), &s)