Mohsen Kamrani
Do10X

Do10X

Parse a JSON file into struct

Mohsen Kamrani's photo
Mohsen Kamrani
·Jul 7, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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)

}

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"
      }
    }
  ]
}

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:

github.com/dotenx/dotenx

 
Share this