go

How to create a POST payload from a slice


Creating payload for the array,POST API call.

pipeline   []struct {
        Test string `json:"$Test"`
    } `json:"pipeline"`

JSON example

{

    "pipeline": [
      {
        "$Test": "test"
      }

    ]
}

For the above struct want to create a POST call request payload like the above JSON structure. I tried different options, but it's not working. What would be the right syntax?


Solution

  • You can try the following code

    package main

    import (
        "encoding/json"
        "fmt"
    )
    
    type TestInt struct{
        Test string `json:"$Test"`
    }
    type Payload struct{
        PipeLine []TestInt `json:"pipeline"`
    }
    
    func main() {
        pl:=Payload{
            PipeLine: []TestInt{
                {
                    Test:"test",
                },
                
            },
        }
        js,_:=json.Marshal(pl)
        fmt.Println(string(js))
    }
    

    See Working link