Search code examples
gogo-gin

How can I form a pretty JSON from a string with backslashes?


I have a Gin-Gonic REST API in Golang. Here I am trying to output users that are already registered as JSON, currently in Postman I only get that:

(You can ignore the lastRequest-Attribut, because it is currently always nil)

"[{\"id\":\"e61b3ff8-6cdf-4b23-97a5-a28107c57543\",\"firstname\":\"John\",\"lastname\":\"Doe\",\"email\":\"john@doe.com\",\"username\":\"johndoe\",\"token\":\"19b33c79-32cc-4063-9381-f2b64161ad8a\",\"lastRequest\":null},

But I want it like this:

[{
        "id": "e61b3ff8-6cdf-4b23-97a5-a28107c57543",
        "username": "johndoe",
        "email": "john@doe.com",
        "token": "19b33c79-32cc-4063-9381-f2b64161ad8a",
        "lastRequest": null
    }]

How do I manage this, I tried many things with the 'json.MarshalIndent' (from this stackoverflow-post), however it didn't change anything for me, what do I need to do? Because the backslashes stay no matter what I do, at most \t or spaces are inserted. I have also read that I have to do it as a byte array, but that didn't work for me either (maybe I did something wrong here too).

Here my current code:


var users []User
r.GET("/getusers", func(c *gin.Context) {
    usersArr := make([]User, len(users))
    for i := 0; i < len(users); i++ {
        usersArr[i] = users[i]
    }
        
    userJson, err := json.Marshal(testUser)
    if err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
    } else {
        c.JSON(200, string(userJson))
    }
})

type User struct {
    Id          string        `json:"id"`
    Firstname   string        `json:"firstname"`
    Lastname    string        `json:"lastname"`
    Email       string        `json:"email"`
    Username    string        `json:"username"`
    Token       string        `json:"token"`
    LastRequest []lastRequest `json:"lastRequest"`
}


Solution

  • Well this would be my first answer in stackoverflow, hope this helps.

    Go gin framework comes with a few handy functions, since I've got no idea what version of golang nor Gin Framework you're using you could try this:

    var users []User
    r.GET("/getusers", func(c *gin.Context) {
        usersArr := make([]User, len(users))
        for i := 0; i < len(users); i++ {
            usersArr[i] = users[i]
        }
            
        if err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
        } else {
            c.JSON(200, users)
    // If Indentation is required you could try:
            c.IndentedJSON(200, users)
        }
    })
    
    type User struct {
        Id          string        `json:"id"`
        Firstname   string        `json:"firstname"`
        Lastname    string        `json:"lastname"`
        Email       string        `json:"email"`
        Username    string        `json:"username"`
        Token       string        `json:"token"`
        LastRequest []lastRequest `json:"lastRequest"`
    }