Home > Blockchain >  List of Go maps to Json
List of Go maps to Json

Time:12-04

I want to parse a list of maps in Go in a json file in a specific format. Following is the list that I have:

m := []map[string]interface{}{}

k1 := map[string]interface{}{"a1": "aa1", "b1": "bb1"}
k2 := map[string]interface{}{"a2": "aa2", "b2": "bb2"}
k3 := map[string]interface{}{"a3": "aa3", "b3": "bb3"}

m = append(m, k1, k2, k3)

This is how I parse it to a json file.

jsonFile, _ := json.MarshalIndent(m, "", "\t")
ioutil.WriteFile("file.json", jsonFile, os.ModePerm)

In the json file, I want:

  • there to be no [ or ] symbols at the beginning or end.
  • Each map to be in a new line
  • there to be no comma between successive maps
  • no space indentation at start of line.

This is how my json file looks at present:

[
    {
        "a1": "aa1",
        "b1": "bb1"
    },
    {
        "a2": "aa2",
        "b2": "bb2"
    },
    {
        "a3": "aa3",
        "b3": "bb3"
    }
]

Below is how I want the output in my saved json file to look:

{
    "a1": "aa1",
    "b1": "bb1"
}
{
    "a2": "aa2",
    "b2": "bb2"
}
{
    "a3": "aa3",
    "b3": "bb3"
}

I realize that I am able to have every map in a new line. So that is done. But, removal of [ or ] symbols, commas after successive maps and indentation is yet to be done. How can I do this?

CodePudding user response:

Your desired output is a series of independent JSON objects. Use a json.Encoder to encode the objects individually.

Something like this:

enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "  ")
for _, v := range m {
    if err := enc.Encode(v); err != nil {
        panic(err)
    }
}

This will output (try it on the Go Playground):

{
  "a1": "aa1",
  "b1": "bb1"
}
{
  "a2": "aa2",
  "b2": "bb2"
}
{
  "a3": "aa3",
  "b3": "bb3"
}

This example writes the JSON text to the standard output. To log to a file, obviously pass an *os.File value instead of os.Stdout.

  • Related