2

I have an example json, the field names aren't really important but the nested values and the data types of some fields are. I understand that in go you have to make sure that when you write to a csv, the data is a string data type when you use csv.Writer. My question is, whats the proper way of writing the nested values, and is there an efficient way to convert all non-string values by iterating through the overall json?

`{
  "name":"Name1",
  "id": 2,
  "jobs":{
      "job1":"somejob",
      "job2":"somejob2"
   },
  "prevIds":{
      "id1": 100,
      "id2": 102
  }
}`

Is the example json

3
  • 1
    Can you show us the expected output? Commented Apr 20, 2016 at 18:33
  • I don't really have an expected output, but want to see what it would look like with a nested json Commented Apr 20, 2016 at 18:42
  • You have written the nested JSON there, so I guess that's your answer? You seem to want to "convert JSON to csv" but that's not descriptive enough. How do you want your own simple example to look as a csv? Commented Apr 20, 2016 at 18:43

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

AH I see! Thank you, this is very informative! Yeah, I wasn't sure how to handle a nested object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.