Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created February 5, 2018 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/62cb5d89bdf2cc596e97ee604431e35f to your computer and use it in GitHub Desktop.
Save tanaikech/62cb5d89bdf2cc596e97ee604431e35f to your computer and use it in GitHub Desktop.
Parsing JSON object (keys are number and changing every time) for golang

Parsing JSON object (keys are number and changing every time) for golang

This sample script is for parsing JSON object. In the object, the keys are number and changing every time.

Object :

{
    "key1": {
        "key2": [
            {"0": [{"key3": "value3a"}, {"key3": "value3b"}]},
            {"1": [{"key3": "value3c"}, {"key3": "value3d"}]}
        ]
    }
}

Script :

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type key1 struct {
    Key1 key2 `json:"key1"`
}

type key2 struct {
    Key2 []interface{} `json:"key2"`
}

func main() {
    data := `{"key1": {"key2": [{"0": [{"key3": "value3a"}, {"key3": "value3b"}]},{"1": [{"key3": "value3c"}, {"key3": "value3d"}]}]}}`
    k1 := &key1{}
    json.Unmarshal([]byte(data), &k1)
    for i, e := range k1.Key1.Key2 {
        if key, ok := e.(map[string]interface{})[strconv.Itoa(i)].([]interface{}); ok {
            for _, f := range key {
                fmt.Printf("%+v\n", f.(map[string]interface{})["key3"])
            }
        }
    }
}

Result :

value3a
value3b
value3c
value3d

The Go Playground

https://play.golang.org/p/xm2KvgOIkKH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment