OneBite.Dev - Coding blog in a bite size

Read json file with random key in Go Lang

How to read a json file that has a dynamic or random key in Go language. We'll use the map data type to solve this

I stumbled upon a case, where i should import bunch of data in JSON to convert to other thing. (I’ll write about this other thing in other post). Go lang become my first language of choice, to do this. Unfortunately the data saved in json each nested in a random key. Here is how i did it

Assume your data looks like this

        "title":"the titls",
        "subject":"the subject"
        "title":"the titls2",
        "subject":"the subject2"

Go gile

In our Go file

package main

import (

type Blogs map[string]Blog

type Blog struct{
    Title string `json:"title"`
    Subject string `json:"desc"`

func main() {
    // Open jsonFile
    jsonFile, err := os.Open("./file.json")

    if err != nil {
    defer jsonFile.Close()

    //convert to byte
    jsonByte, _ := ioutil.ReadAll(jsonFile)

        json.Unmarshal(jsonByte, &blogs)

    for k, v := range blogs {
        fmt.Println("k: ", k, "v: ", v.Title)