Parse a JSON into struct

Sam - Jul 7 '22 - - Dev Community

This short snippet shows you how to parse a JSON with a generic, random structure, stored in a file.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {

    path := "./obj.json"

    jsonFile, err := os.Open(path)
    if err != nil {
        fmt.Println(err)
    }
    defer jsonFile.Close()
    bytes, _ := ioutil.ReadAll(jsonFile)

    var parsed map[string]interface{}
    json.Unmarshal([]byte(bytes), &parsed)
    fmt.Printf("%#v", parsed)

}
Enter fullscreen mode Exit fullscreen mode

To test the code, you can use a json file like this:

obj.json

{
  "prop": "value",
  "students": [
    {
      "name": "John",
      "age": "20",
      "marks": "80",
      "address": {
        "city": "New York",
        "state": "NY"
      }
    },
    {
      "name": "Jane",
      "age": "20",
      "marks": "90",
      "address": {
        "city": "New York",
        "state": "NY"
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

The output for this example would be like this:

map[string]interface {}{"prop":"value", "students":[]interface {}{map[string]interface {}{"address":map[string]interface {}{"city":"New York", "state":"NY"}, "age":"20", "marks":"80", "name":"John"}, map[string]interface {}{"address":map[string]interface {}{"city":"New York", "state":"NY"}, "age":"20", "marks":"90", "name":"Jane"}}}%

map[string]interface {}{"prop":"value", "students":[]interface {}{map[string]interface {}{"address":map[string]interface {}{"city":"New York", "state":"NY"}, "age":"20", "marks":"80", "name":"John"}, map[string]interface {}{"address":map[string]interface {}{"city":"New York", "state":"NY"}, "age":"20", "marks":"90", "name":"Jane"}}}%

Note: if your JSON object has a format you know beforehand, you can use a struct instead of map[string]interface{}


I'm the maintainer of DoTenX, and invite you to take a look at this repository, if you enjoy coding with Golang or learning it:

https://github.com/dotenx/dotenx

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .