登录
首页 >  Golang >  Go问答

在 Go 中将动态 JSON 转换为 CSV

来源:stackoverflow

时间:2024-02-07 09:18:25 340浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《在 Go 中将动态 JSON 转换为 CSV》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我尝试将动态 json 转换为 csv,我调查了库和答案,但找不到什么了不起的东西。

这个和这个示例可能会有所帮助,但我无法将 json 的结构添加到我的代码中,json 是动态的。

在 python & js 中,我看到了这些例子;

python;

# python program to convert
# json file to csv
 
 
import json
import csv
 
 
# opening json file and loading the data
# into the variable data
with open('data.json') as json_file:
    data = json.load(json_file)
 
employee_data = data['emp_details']
 
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
 
# create the csv writer object
csv_writer = csv.writer(data_file)
 
# counter variable used for writing
# headers to the csv file
count = 0
 
for emp in employee_data:
    if count == 0:
 
        # writing headers of csv file
        header = emp.keys()
        csv_writer.writerow(header)
        count += 1
 
    # writing data of csv file
    csv_writer.writerow(emp.values())
 
data_file.close()

js;

const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = object.keys(items[0])
const csv = [
  header.join(','), // header row first
  ...items.map(row => header.map(fieldname => json.stringify(row[fieldname], replacer)).join(','))
].join('\r\n')

console.log(csv)

这些代码有助于轻松将动态 json 转换为 csv。

输入和输出示例;

json(输入);

[
  {
    "name": "john",
    "age": "21"
  },
  {
    "name": "noah",
    "age": "23"
  },
  {
    "name": "justin",
    "age": "25"
  }
]

csv(输出);

"name","age"
"John","21"
"Noah","23"
"Justi","25"

那么如何在 go 中将动态 json 转换为 csv?

ps:我发现一个 golang lib(json2csv) 可以帮助转换,但只能在命令提示符下工作。

例如,我很少使用在线工具;

https://csvjson.com/json2csv

https://data.page/json/csv


正确答案


经过调查,我用 yukithm/json2csv 包来处理。

package main

import (
    "bytes"
    "encoding/json"
    "github.com/yukithm/json2csv"
    "log"
    "os"
)

func main() {
    b := &bytes.buffer{}
    wr := json2csv.newcsvwriter(b)
    j, _ := os.readfile("your-input-path\\input.json")
    var x []map[string]interface{}

    // unmarshall json
    err := json.unmarshal(j, &x)
    if err != nil {
        log.fatal(err)
    }

    // convert json to csv
    csv, err := json2csv.json2csv(x)
    if err != nil {
        log.fatal(err)
    }

    // csv bytes convert & writing...
    err = wr.writecsv(csv)
    if err != nil {
        log.fatal(err)
    }
    wr.flush()
    got := b.string()

    //following line prints csv
    println(got)

    // create file and append if you want
    createfileappendtext("output.csv", got)
}

//
func createfileappendtext(filename string, text string) {
    f, err := os.openfile(filename, os.o_append|os.o_wronly|os.o_create, 0600)
    if err != nil {
        panic(err)
    }

    defer f.close()

    if _, err = f.writestring(text); err != nil {
        panic(err)
    }
}

input.json;

[
  {
    "name": "japan",
    "capital": "tokyo",
    "continent": "asia"
  },
  {
    "name": "germany",
    "capital": "berlin",
    "continent": "europe"
  },
  {
    "name": "turkey",
    "capital": "ankara",
    "continent": "europe"
  },
  {
    "name": "greece",
    "capital": "athens",
    "continent": "europe"
  },
  {
    "name": "israel",
    "capital": "jerusalem",
    "continent": "asia"
  }
]

输出.csv

/capital,/continent,/name
tokyo,asia,japan
berlin,europe,germany
ankara,europe,turkey
athens,europe,greece
jerusalem,asia,israel

将其粘贴到 https://github.com/yukithm/json2csv/blob/master/cmd/json2csv/main.go 并将 func 插入 main。

func stackoverflow() {

    jsonstr := `
[
  {
    "name": "john",
    "age": "21"
  },
  {
    "name": "noah",
    "age": "23"
  },
  {
    "name": "justin",
    "age": "25"
  }
]`

    buff := bytes.newbufferstring(jsonstr)

    data, _ := readjson(buff)

    results, _ := json2csv.json2csv(data)

    headerstyle := headerstyletable["jsonpointer"]
    err := printcsv(os.stdout, results, headerstyle, false)
    if err != nil {
        log.fatal(err)
    }
}

这对我有用。

➜  json2csv git:(master) ✗ go run main.go 
/age,/name
21,John
23,Noah
25,Justin

今天关于《在 Go 中将动态 JSON 转换为 CSV》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>