Is there a way to loop over a json file and get each struct into a separate file — Golang?

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

Is there a way to loop over a json file and get each struct into a separate file -- Golang?

问题

所以我的程序是读取一个CSV文件并将其转换为JSON。我已经能够做到这一点,并将JSON写入文件,但我希望能够将该JSON文件中的每个结构或对象写入另一个文件。

我附上了我的代码以便更好地理解:

package main

import (
	"crypto/sha256"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strconv"
)

type NftRecord struct {
	SeriesNumber int    `json:"Series Number"`
	Name         string `json:"Name"`
	Hash         string `json:"Hash"`
	UUIDs        string `json:"UUIDs"`
	Description  string `json:"Description"`
	DriveLink    string `json:"Drive Link"`
}

func createRecordsList(data [][]string) []NftRecord {
	var recordList []NftRecord
	for i, line := range data {
		if i > 0 {
			var rec NftRecord
			for j, field := range line {
				if j == 0 {
					var err error
					rec.SeriesNumber, err = strconv.Atoi(field)
					if err != nil {
						continue
					}
				} else if j == 4 {
					rec.Name = field
				} else if j == 7 {
					rec.Description = field
				} else if j == 6 {
					rec.UUIDs = field
				} else if j == 5 {
					rec.Hash = field
				} else if j == 8 {
					rec.DriveLink = field
				} else if j == 13 {
					var err error
					if err != nil {
						continue
					}
				}
			}
			recordList = append(recordList, rec)
		}
	}
	return recordList
}

func main() {
	f, err := os.Open("./scaler.csv")
	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	csvReader := csv.NewReader(f)
	data, err := csvReader.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	recordList := createRecordsList(data)

	jsonData, err := json.MarshalIndent(recordList, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	_ = ioutil.WriteFile("./test.json", jsonData, 0644)

	fmt.Println(string(jsonData))

	//hashing
	hash := sha256.New()
	if _, err := io.Copy(hash, f); err != nil {
		panic(err)
	}

	sum := fmt.Sprintf("%x", hash.Sum(nil))
	fmt.Println(sum)
}

我已经尝试了几乎所有的方法,希望能够解决这个问题,因为我还有其他功能要添加。

这是下面的JSON:

{
  "Series Number": 301,
  "Name": "wendy-the -banker",
  "Hash": "D615D6E161E5F820A2B9F5C3ED3867BE0AA9F16DDCA00A0550E30E29A0B467AD",
  "UUIDs": "587645e2-5ace-11ed-9b6a-0242ac120002",
  "Description": "Wendy喜欢在银行工作,因为她可以遇到不同的人。",
  "Drive Link": "Link"
},
{
  "Series Number": 302,
  "Name": "uduak-the -dark horse",
  "Hash": "5A63A94F455D367EC0AA39F57F827DDBECD3F335C817ED5A76460A2AB8E9068A",
  "UUIDs": "58764862-5ace-11ed-9b6a-0242ac120002",
  "Description": "Uduak看起来很无辜,但整个公寓都被窃听了",
  "Drive Link": "Link"
}

希望对你有帮助!

英文:

So my program is to read through a csv file and convert it into json. i've been able to do that and write the json to a file however i want to be able to take each struct or object from this json file and write to a file.

i've attached my code for more understanding

package main
import (
"crypto/sha256"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strconv"
)
type NftRecord struct{
SeriesNumber     int    `json:"Series Number"`
Name             string `json:"Name"`
//TheDescriptor    string `json:"The Descriptor"`
//NewName          string `json:"New Name"`
Hash             string `json:"Hash"`
UUIDs            string `json:"UUIDs"`
Description      string `json:"Description"`
DriveLink        string `json:"Drive Link"`
}
func createRecordsList(data [][]string) []NftRecord{
var recordList []NftRecord
for i, line := range data{
if i > 0{
var rec NftRecord
for j, field := range line{
if j == 0{
var err error
rec.SeriesNumber, err = strconv.Atoi(field)
if err != nil{
continue
}
}else if j == 4{
rec.Name = field
}else if j == 7 {
rec.Description = field
}else if j ==6{
rec.UUIDs = field
}else if j == 5{
rec.Hash = field
}else if j == 8{
rec.DriveLink = field
} else if j == 13{
var err error 
if err != nil{
continue
}
}
}
recordList = append(recordList, rec)
}
}
return recordList
}
func main(){
f, err := os.Open("./scaler.csv")
if err != nil {
log.Fatal(err)
}
defer f.Close()
csvReader := csv.NewReader(f)
data, err := csvReader.ReadAll()
if err != nil {
log.Fatal(err)
}
recordList := createRecordsList(data)
jsonData, err := json.MarshalIndent(recordList, "", "  ")
if err != nil {
log.Fatal(err)
}
_ = ioutil.WriteFile("./test.json", jsonData, 0644)
fmt.Println(string(jsonData))
//hashing
hash := sha256.New()
if _, err := io.Copy(hash, f); err != nil {
panic(err)
}
sum := fmt.Sprintf("%x", hash.Sum(nil))
fmt.Println(sum)
}

i've tried pretty much everything i guess, i'm hoping i could get past this as i've got other features to add.

This is the JSON below

{
  "Series Number": 301,
  "Name": "wendy-the -banker",
  "Hash": "D615D6E161E5F820A2B9F5C3ED3867BE0AA9F16DDCA00A0550E30E29A0B467AD",
  "UUIDs": "587645e2-5ace-11ed-9b6a-0242ac120002",
  "Description": "Wendy loves working in the bank, as she gets to meet different people.",
  "Drive Link": "Link"
},
{
  "Series Number": 302,
  "Name": "uduak-the -dark horse",
  "Hash": "5A63A94F455D367EC0AA39F57F827DDBECD3F335C817ED5A76460A2AB8E9068A",
  "UUIDs": "58764862-5ace-11ed-9b6a-0242ac120002",
  "Description": "Uduak looks innocent and has the whole apartment bugged",
  "Drive Link": "Link"
},

答案1

得分: 1

循环遍历recordList。对于每个元素,将其转换为JSON并写入一个唯一的文件。你需要有一个唯一的文件命名方案,但一个简单的实现方式是使用计数器(例如1.json,2.json等)。

英文:

Loop over recordList. For each element marshall it to JSON and write it to a unique file. You’ll have to have a unique file naming scheme but a trivial one to implement would be a counter (eg 1.json, 2.json, etc).

huangapple
  • 本文由 发表于 2022年11月3日 16:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/74299944.html
匿名

发表评论

匿名网友

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

确定