'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 1:[1]

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.

Solution 2:[2]

A type safe way to do this would be creating a struct that represents your request object and unmarshalling it.

This gives you a panic on unexpected requests.

package main

import (
    "encoding/json"
    "fmt"
)

type response struct {
    Endpoint string
}

func main() {
    jsonBody := []byte(`{"endpoint": "assistance"}`)
    data := response{}
    
    if err := json.Unmarshal(jsonBody, &data); err != nil {
        panic(err)
    }

    fmt.Println(data.Endpoint)
}
// assistance

This program as an example safely decodes the JSON into a struct and prints the value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Lex