Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List of Go maps to Json

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading