-1

I am building a body for a POST request

relativeurl := "this-is-a-test-url"

postBody := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": \"%s\"}]}", relativeurl)

When I do a fmt.Println of postBody, I see:

{
"requests": [
    {
        "httpMethod": "GET",
        "relativeUrl": "this-is-a-test-url"}]}

but the url is expecting a JSON:

{
    "requests": [
        {
            "httpMethod": "GET",
            "relativeUrl": "this-is-a-test-url"
        }
]
}

Is the way I build the post body wrong?

Grokify
  • 15,092
  • 6
  • 60
  • 81
  • 1
    Check this out https://yourbasic.org/golang/json-example/ – Chen A. Jul 19 '21 at 07:01
  • 3
    Use the [json](https://pkg.go.dev/encoding/json) package. – Jonathan Hall Jul 19 '21 at 07:01
  • Unless I'm missing something, I see twice the same valid json payloads -- the only difference is in the formatting. The only possible issue I see is the lack of json escaping on the `relativeUrl` value. Were you looking for something more ? – LeGEC Jul 19 '21 at 07:40

3 Answers3

2

Just to mention another way to correctly escape a JSON string :

// call the json serializer just on the string value :
escaped, _ := json.Marshal(relativeUrl)
// the 'escaped' value already contains its enclosing '"', no need to repeat them here :
body := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": %s}]}", escaped)

https://play.golang.org/p/WaT-RCnDQuK

LeGEC
  • 46,477
  • 5
  • 57
  • 104
1

Your two JSON output examples are both valid and functionally equivalent. White space is not significant in JSON. See the following at JSON.org:

Whitespace can be inserted between any pair of tokens.

You can test and format your JSON easily using encoding/json or an online JSON parser.

However, the approach you are using is prone to error since your URL needs to be properly escaped. For example, if your URL has a double quote, ", in it, your code will produce invalid JSON.

In Go, it's much better to create some structs to encode. For example:

package main

import (
    "encoding/json"
    "fmt"
)

type RequestBody struct {
    Requests []Request `json:"requests"`
}

type Request struct {
    HTTPMethod  string `json:"httpMethod"`
    RelativeURL string `json:"relativeUrl"`
}

func main() {
    body := RequestBody{
        Requests: []Request{{
            HTTPMethod:  "GET",
            RelativeURL: "this-is-a-test-url",
        }},
    }

    bytes, err := json.MarshalIndent(body, "", "  ")
    if err != nil {
        panic(err)
    }

    fmt.Println(string(bytes))
}

Here's a running example:

https://play.golang.org/p/c2iU6blG3Rg

Grokify
  • 15,092
  • 6
  • 60
  • 81
0

You can use json package to handle json inputs and outputs. Use json.Unmarshal function to convert json to golang structure and use json.Marshal function to convert golang structure to json.

mshomali
  • 664
  • 1
  • 8
  • 27