A working example is below:
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
)
func decodeJson(m map[string]interface{}) []string {
values := make([]string, 0, len(m))
for _, v := range m {
switch vv := v.(type) {
case map[string]interface{}:
for _, value := range decodeJson(vv) {
values = append(values, value)
}
case string:
values = append(values, vv)
case float64:
values = append(values, strconv.FormatFloat(vv, 'f', -1, 64))
case []interface{}:
// Arrays aren't currently handled, since you haven't indicated that we should
// and it's non-trivial to do so.
case bool:
values = append(values, strconv.FormatBool(vv))
case nil:
values = append(values, "nil")
}
}
return values
}
func main() {
var d interface{}
err := json.Unmarshal(exampleJSON, &d)
if err != nil {
log.Fatal("Failed to unmarshal")
}
values := decodeJson(d.(map[string]interface{}))
fmt.Println(values)
f, err := os.Create("outputfile.csv")
if err != nil {
log.Fatal("Failed to create outputfile.csv")
}
defer f.Close()
w := csv.NewWriter(f)
if err := w.Write(values); err != nil {
log.Fatal("Failed to write to file")
}
w.Flush()
if err := w.Error(); err != nil {
log.Fatal("Failed to flush outputfile.csv")
}
}
var exampleJSON []byte = []byte(`{
"name":"Name1",
"id": 2,
"jobs":{
"job1":"somejob",
"job2":"somejob2"
},
"prevIds":{
"id1": 100,
"id2": 102
}
}`)
This works by decoding the arbitrary JSON as shown in this goblog post then iterating and handling each possible type by converting it to string in the usual way. If you come across a map[string]interface{}
, then you're recursing to get the next set of data.
Once you've got a []string
, you can pass it to your csv.Writer
to write out however you like. In this case the output is
Name1,2,somejob,somejob2,100,102