📚Cheatsheets

Cheatsheet collection for go, rust and javascript.

Parsing JSON with dynamic key

Most of the time we will parse JSON data to struct.

type User struct {
    Username string `json:"username"`
    Email string `json:"email"`
}

But if you have JSON data like this, you can not parse that directly to the struct.

{
    "0": {
        "username":"ahmad",
        "email":"ahmad@mail.com",
    },
    "1": {
        "username":"ahmad1",
        "email":"ahmad1@mail.com",
    }
}

So to solve this you can create map to user.

type Response map[string]User

So you can parse it like this.

import (
    "strings"
    "encoding/json"
)

func Parse(data string) {
    dec := json.NewDecoder(strings.NewReader(data))
    var response Response
    dec.Decode(&response)
    response["0"].username // ahmad
    response["1"].username // ahmad1
}