Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang is there an easy way to unmarshal arbitrary complex json

Tags:

go

Every example I come to online shows examples of building structs for the data and then unmarshaling JSON into the data type. The problem is that what I am getting is massive dump of JSON and it seems like backbreaking labor to use such a method....

Is there a way to take a huge dump of data and get it to unmarshal into a map like object that would function similar to json/maps?

What I have right now is like this...

var data map[interface{}]interface{}
err = json.Unmarshal(JSONDUMP, &data)
if err != nil { log.Fatal(err) }

but then I cannot call it like this

data["some"]["long"]["chain"]["of"]["lookups"] 
(type interface {} does not support indexing)
like image 933
Joff Avatar asked Feb 10 '17 06:02

Joff


1 Answers

In general this is a bad idea! But if you really need, you can do like this:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var anyJson map[string]interface{}

    customJSON := []byte(`{"a": "text comes here", "b": {"c":10, "d": "more text"}}`)

    json.Unmarshal(customJSON, &anyJson)

    fmt.Println("a ==", anyJson["a"].(string))

    b_temp := anyJson["b"].(map[string]interface{})
    fmt.Println("c ==", b_temp["c"].(float64))
}

.. then you can use any field like anyJson["a"].(string) - look at type assertion, it's critically important to be valid

like image 52
Alexey Avatar answered Oct 16 '22 20:10

Alexey