Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created Feb 5, 2018
Embed
What would you like to do?
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