From 0b8d8dd8ce5e873b5a3bcdd0eb83a303f0a28bec Mon Sep 17 00:00:00 2001 From: Orhan Erday <98099231+orhan-erday@users.noreply.github.com> Date: Mon, 22 Aug 2022 08:50:05 +0300 Subject: [PATCH] Added usage at code part --- README.md | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/README.md b/README.md index f9c4c39..ea8fdef 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,106 @@ Note: `slash` style similar to `jsonpointer` style, but `slash` style doesn't st Note: `dot-bracket` style similar to `dot` style, but `dot-bracket` style uses square brackets for array indexes. +### Usage on code + + 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" + } + ] + +***output.csv*** + + /Capital,/Continent,/Name + Tokyo,Asia,Japan + Berlin,Europe,Germany + Ankara,Europe,Turkey + Athens,Europe,Greece + Jerusalem,Asia,Israel + + License -------