How to accesar map coming from a JSON without creating structs?

Asked

Viewed 146 times

1

After taking some data from an endpoint I get passes to a variable of type interface{};

var example interface{}
err := json.Unmarshal(payload, &example)

If I run a fmt.Println(example) have the following data:

map[ticker:map[last:28533.87000000 buy:28320.00006000 sell:28533.79000000 date:1.527794277e+09 high:28599.00000000 low:27700.00001000 vol:55.58867619]]

In case I try to access some value with example["ticker"] I have the following error:

invalid Operator: quotation["Ticker"] (type interface{} does not support Indexing)

Before compiling the code the analysis done is that type interface has no indices (what is correct).

But if I can store the data in one interface{} consequently I could access them correctly? how can I access this data without this error in the compilation?

1 answer

1


I believe that using the interface{} is not ideal. When you use the interface there is no type "associated" to it explicitly, you will always need to use the "type assertions".


JSON will be a map[string]interface{} (or a []interface{}, if it’s just an array, no objects, but I’m not sure about that!).

In this case, for you to access the example["ticker"] the example needs to be a map[string]Tipo, to do so:

exampleMap := example.(map[string]interface{})

Now yes, the exampleMap will be a map[string] and you can access ticker. However, the ticker is also a interface{} and you will also have to define his type and so on.


I don’t know if I understood JSON correctly, but apparently this would get the last, for example:

var example interface{}
json.Unmarshal(payload, &example)

exampleMap := example.(map[string]interface{})
tickerMap := exampleMap["ticker"].(map[string]interface{})

fmt.Print(tickerMap["last"].(float64))

You can reduce a little if you specify the example for map[string]interface{} instead of interface{}, as:

var example map[string]interface{}
json.Unmarshal(payload, &example)

tickerMap := example["ticker"].(map[string]interface{})

fmt.Print(tickerMap["last"].(float64))

But it’s even more confusing than using the struct directly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.