如何解析json数组结构

我使用以下代码没有成功解析 json 值,但它的内部数组 []


https://play.golang.org/p/5HdWeyEtvie


package main


import (

    "encoding/json"

    "fmt"

)



var input = `

[

{

    "created_at": "Thu May 31 00:00:01 +0000 2012"

},

{

    "created_at": "Thu May 31 00:00:01 +0000 2012"

}

]

`


func main() {

    var val map[string]interface{}

    if err := json.Unmarshal([]byte(input), &val); err != nil {

        panic(err)

    }

    fmt.Println(val)

}

这个想法是获取值作为键并打印它,就像获取字符串参数 =“created_at” 并打印它的函数一样。


收到一只叮咚
浏览 181回答 4
4回答

杨__羊羊

您的输入是:[     {        "created_at":"Thu May 31 00:00:01 +0000 2012"   },   {        "created_at":"Thu May 31 00:00:01 +0000 2012"   }]你可以把它变成这样的结构:type MyArray []struct {    CreatedAt string `json:"created_at"`}现在您可以读取 JSON 数据并循环遍历它以获得所需的值。这是你得到的:package mainimport (    "encoding/json"    "fmt")var str = `[    {    "created_at": "Thu May 31 00:00:01 +0000 2012"    },    {    "created_at": "Thu May 31 00:00:01 +0000 2013"    }]`type MyArray struct {    CreatedAt string `json:"created_at"`}func main() {    var m []MyArray    if err := json.Unmarshal([]byte(str), &m); err != nil {        panic(err)    }    for _, val := range m {        fmt.Println(val.CreatedAt)    }}

青春有我

您正在将数组解组到地图。这显然行不通。你需要val是一个数组。func main() {&nbsp; &nbsp; var val []map[string]interface{} // <---- This must be an array to match input&nbsp; &nbsp; if err := json.Unmarshal([]byte(input), &val); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(val)}

宝慕林4294392

var input = `[&nbsp; &nbsp; {&nbsp; &nbsp; "created_at": "Thu May 31 00:00:01 +0000 2012"&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; "created_at": "Thu May 31 00:00:01 +0000 2013"&nbsp; &nbsp; }]`func main() {&nbsp; &nbsp; var val []struct {&nbsp; &nbsp; &nbsp; &nbsp; CreatedAt string `json:"created_at"`&nbsp; &nbsp; }&nbsp; &nbsp; if err := json.Unmarshal([]byte(input), &val); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(val[0].CreatedAt)}

慕少森

你应该像这样创建一个结构。type Data struct {&nbsp; &nbsp; CreateAt time.Time `json:"create_at"`}func main() {&nbsp; &nbsp; var in []Data&nbsp; &nbsp; if err := json.Unmarshal([]byte(input), &in); err != nil{&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; for _, data := range in{&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(data.CreateAt)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go