0

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"]) 
jub0bs
  • 60,866
  • 25
  • 183
  • 186

2 Answers2

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.

Lex
  • 4,749
  • 3
  • 45
  • 66
0

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.

Matthieu
  • 36
  • 3
  • https://golang.org/ref/spec#Conversions https://golang.org/ref/spec#Type_assertions details –  Aug 14 '21 at 10:49