Add values to map[string]interface{}

9,025 views
Skip to first unread message

User123

unread,
Mar 18, 2015, 6:01:05 AM3/18/15
to golan...@googlegroups.com
I am new to golang. 

I am trying to create an object which looks like this:

ACK: "Success"
BUILD: "15420584"
CORRELATIONID: "1eac210c7c07a"
TIMESTAMP: "2015-03-17T11:08:47Z"
VERSION: "69.0"
ITEMS:
 0: 
  AMT: "60.00"
  CURRENCYCODE: "USD"
  FEEAMT: "0.00"
  NAME: "Test Store"
  NETAMT: "60.00"
  STATUS: "Completed"
  TIMESTAMP: "2014-03-11T07:52:05Z"
  TIMEZONE: "GMT"
  TRANSACTIONID: "9F4923492C3800000"
  TYPE: "Payment"
 1: ....

Here's the code for that. But it gives an error invalid operation: finalResult["ITEMS"]["0"] (type interface {} does not support indexing)

I don't want to use struct for finalResult since the total key and their names can vary

finalResult := make(map[string]interface{})
type itemVaues map[string]string
finalResult["ITEMS"] = make(map[string]itemVaues)


if _, ok := finalResult["ITEMS"]["0"]; !ok {
tempMap := make(itemVaues)
tempMap["ACK"] = "Success"
tempMap["CURRENCYCODE"] = "USD"
    finalResult["ITEMS"]["0"] = tempMap   
    fmt.Println("finalResult",finalResult)
}

Please help.

Grzegorz Żur

unread,
Mar 18, 2015, 6:41:20 AM3/18/15
to golan...@googlegroups.com
Hi,

You need to make type assertion of the interface{} value from map.

finalReslut["ITEMS"].(map[string]interface{})["0"]

Grzegorz Żur

Egon

unread,
Mar 18, 2015, 6:57:47 AM3/18/15
to golan...@googlegroups.com
First, use play.golang.org to submit examples/problems - it makes it easier for other people to help you.


Although, I would strongly recommend using structs instead, they will make errors less likely... There probably is a nicer/cleaner solution using structs and that can satisfy your requirements.

+ Egon

User123

unread,
Mar 18, 2015, 7:35:24 AM3/18/15
to golan...@googlegroups.com
I made type assertion of final result to (map[string]itemVaues) like this: https://play.golang.org/p/z09cAZ3FIu

Is it correct?
Reply all
Reply to author
Forward
0 new messages