解码并追加到数组中的Go代码。

huangapple go评论85阅读模式
英文:

Unmarshal and append to array go

问题

我正在从S3中读取多个JSON文件,并希望将它们作为一个大的JSON数组返回。我有一个与我的JSON数据匹配的结构体,并且有一个循环遍历我的S3存储桶中的所有对象。每次读取时,我将其解组为我的结构体数组。我想要将数据追加到结构体数组中,以便获取所有的JSON数据,而不仅仅是一个文件的数据。在Golang中有没有办法做到这一点?

英文:

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

得分: 3

是的,你应该创建一个临时数组来解析每个JSON的内容,然后将项目追加到最终的结果数组中,以便将整个集合作为一个项目返回。

以下是一个示例:

在你的情况下,input将来自你提到的每个S3文件。此外,你可能会将解析逻辑放在自己的函数中,以便能够为每个输入的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

英文:

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

huangapple
  • 本文由 发表于 2017年7月8日 07:23:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/44980953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定