douqiao6015 2014-04-25 07:46
浏览 1142
已采纳

如何在Golang中遍历JSON数组?

I am trying to decode a JSON array and put it in a slice of a struct. I've read how to do this, but only if the JSON array contains keys. My JSON array does not contain keys.

I have stripped the program down to only the part where it handles the JSON data. It compiles and can be found below.

package main

// 2014-04-19

import (
    "fmt"
    "encoding/json"
)

type itemdata struct {
    data1 int // I have tried making these strings
    data2 int
    data3 int
}

func main() {
    datas := []itemdata{}

    json.Unmarshal([]byte(`[["7293","1434","99646"],["4657","1051","23795"]]`), &datas)
    // I have tried the JSON string without the qoutes around the numbers
    fmt.Println(len(datas)) // This prints '2'
    fmt.Println("This prints") // This does print 
    for i := range datas {
        fmt.Println(datas[i].data1)  // This prints '0', two times 
    }
    fmt.Println("And so does this") // This does print
}

I've searched for things like 'Go Lang JSON decode without keys' and read articles (and 'package pages') on the Go Lang website. I can find enough information on how to work with Go and JSON, but none of my found articles explain how to do it without keys in the JSON array.

I wouldn't find it odd if I would get an error; The JSON values are stringy-numbers (that's how I get them as input), but I am trying to put them in integers. I am not getting an error though. I have tried making the values in the 'itemdata' struct strings, that didn't help much. Removing the quotes from the JSON values didn't help either.

I would like to know how I can make my JSON array in a slice of 'itemdata'. The first out of three values would go into 'itemdata.data1', the second in 'itemdata.data2' and the third in 'itemdata.data3'.

Please let me know if you think I can improve my question.

Thanks in advance,
Remi

  • 写回答

1条回答 默认 最新

  • dongzexi5125 2014-04-25 07:50
    关注

    What you have here is a bi-dimensional array of strings. You can decode it like this :

    type itemdata [][]string
    
    func main() {
       var datas itemdata
    
        json.Unmarshal([]byte(`[["7293","1434","99646"],["4657","1051","23795"]]`), &datas)
        fmt.Println(len(datas))
        fmt.Println("This prints")
        for i := range datas {
            fmt.Println(datas[i][1]) 
        }
        fmt.Println("And so does this")
    }
    

    Demonstration

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd