duan00529
2016-08-10 08:11
采纳率: 100%
浏览 1.7k
已采纳

如何在 Golang 中解析 JSON 数组?

一个简单的问题:如何使用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)
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyan4958 2016-08-10 08:18
    已采纳

    The return value of Unmarshal is an err, and this is what you are printing out:

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

    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]
    

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dsjuimtq920056 2016-08-10 08:16

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

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

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

    Arrays can be unmarshaled into Go arrays or slices. So pass 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):

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

    Of course you don't even need the JsonType wrapper, just use a simple []string slice:

    dataJson := `["1","2","3"]`
    var s []string
    err := json.Unmarshal([]byte(dataJson), &s)
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题