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

1

After getting some data from an endpoint I can pass them to a variable of type interface{} ;

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

If I run a fmt.Println(example) I 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]]

If I try to access some value with example["ticker"] I get 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 (which is correct).

But if I can store the data in a interface{} consequently I could access them correct? how can I access this data without this compile error occurring?

    
asked by anonymous 31.05.2018 / 21:25

1 answer

1

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

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

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

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

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

I do not know if I understood JSON correctly, but apparently it would get 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 narrow down a bit by specifying the example to map[string]interface{} instead of interface{} , such 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 struct directly.

    
01.06.2018 / 04:10