2

I've created a web server and this server is able to get POST request. However, when I send array of map[string]string in POST data, server receives it as array of interface{}. How can I convert it back to array of map[string]string?

Example : Like when I send following example in POST request,

params : [{"name" : "shail", "age" : 24}]

I'm sending params as

[](map[string]string)

but when server receives this data, it treats params as

[]interface{}

.How do I assign params in a variable defined by

[](map[string]interface{})

?

2
  • 2
    What do you mean by "when I send?" Do you Marshall this into JSON and then Unmarshall it? How are you Unmarshalling it? Are you sending GOB instead of JSON? What code you "receives it as array of interface{}?" There is no standard web protocol that sends "interface{}". Have you looked at the examples in encoding/json? Commented Aug 29, 2015 at 22:42
  • 2
    Agreed. I provided an admittedly dumb answer below - you can Unmarshal the JSON payload on a struct and get type safety and more code clarity..... Commented Aug 29, 2015 at 22:45

1 Answer 1

1

The easiest thing you can do is a type assertion on the values:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var source []interface{}
    var test = make(map[string]string, 0)
    test["hello"] = "World"
    source = append(source, test)
    var dest = source[0].(map[string]string)
    fmt.Println(reflect.TypeOf(dest).Kind())
    fmt.Println(dest["hello"])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.