Home > Enterprise >  How to return a struct as a one-element JSON array in Gin?
How to return a struct as a one-element JSON array in Gin?

Time:07-17

I have a function that returns a product by its ID, but the problem is that it does not return it as a data array

func GetProductsById(c *gin.Context) {
    var Product models.Products
    if err := config.DB.Where("id=?", c.Query("prod_id")).First(&Product).Error; err != nil {
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        c.JSON(http.StatusOK, gin.H{"data": &Product})
    }
}

json response

{
    "data": {
        "ID": 1,
        ...
        "Feedback": null
    }
}

I want this:

{
    "data": [{
        "ID": 1,
        ...
        "Feedback": null
    }]
}

CodePudding user response:

As suggested by @mkopriva, to easily return a struct as a single-element JSON array, wrap it in a slice literal.

var p models.Product
// ...
c.JSON(http.StatusOK, gin.H{"data": []models.Product{p}})

If you don't want to specify a particular type for the slice items, you can use []interface{}, or []any starting from Go 1.18

c.JSON(http.StatusOK, gin.H{"data": []interface{}{p}})
// c.JSON(http.StatusOK, gin.H{"data": []any{p}})
  • Related