duanji6997 2017-07-07 23:23
浏览 77
已采纳

解组并追加到数组go

I'm reading a number of JSON files from S3, and want to return them all as one large JSON array. I have a struct matching my JSON data, and a for loop iterating over all objects in my s3 bucket. Each time I read, I unmarshal to my struct array. I want to append to my struct array so that I can get all the JSON data rather than just one file's data. Is there anyway to do this in Golang?

  • 写回答

1条回答 默认 最新

  • drgc9632 2017-07-08 00:08
    关注

    Yes, you should create a temporary array to Unmarshal the contents of each JSON, then append the items to your final result array in order to return the whole collection as one item.

    See here an example of doing that.

    In your case input would come from each of the S3 files you mention. Also, you would probably put that unmarshal logic in its own function to be able to call it for each input JSON.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    type Record struct {
        Author string `json:"author"`
        Title  string `json:"title"`
    }
    
    func main() {
        var allRecords []Record
    
        input := []byte(`[{
          "author": "Nirvana",
          "title":  "Smells like teen spirit"
        }, {
          "author": "The Beatles",
          "title":  "Help"
        }]`)
    
        var tmpRecords []Record
        err := json.Unmarshal(input, &tmpRecords)
        if (err != nil) {
            log.Fatal(err)
        }
    
        allRecords = append(allRecords, tmpRecords...)  
    
        fmt.Println("RECORDS:", allRecords)
    }
    

    https://play.golang.org/p/ZZGhy4UNhP

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭