Search code examples
jsongogo-echo

How to convert json to string in golang and echo framework?


I have a json that I receive by post

{"endpoint": "assistance"}

I receive this like this

json_map: = make (map[string]interface{})

Now I need to assign it to a variable as a string but I don't know how to do it.

endpoint: = c.String (json_map ["endpoint"]) 

Solution

  • What you are trying to achieve is not to convert a JSON to a string but an empty interface interface{} to a string You can achieve this by doing a type assertion:

    endpoint, ok := json_map["endpoint"].(string)
    if !ok {
      // handle the error if the underlying type was not a string
    }
    

    Also as @Lex mentionned, it would probably be much safer to have a Go struct defining your JSON data. This way all your fields will be typed and you will no longer need this kind of type assertion.