英文:
How can I form a pretty JSON from a string with backslashes?
问题
我有一个Gin-Gonic REST API,使用Golang编写。我想将已注册的用户以JSON格式输出,但目前在Postman中只能得到以下结果:
(你可以忽略lastRequest
属性,因为它目前始终为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},
但我希望得到以下格式:
[{
"id": "e61b3ff8-6cdf-4b23-97a5-a28107c57543",
"username": "johndoe",
"email": "john@doe.com",
"token": "19b33c79-32cc-4063-9381-f2b64161ad8a",
"lastRequest": null
}]
我该如何处理这个问题?我尝试了很多方法,包括使用[json.MarshalIndent][3]
(来自这个stackoverflow帖子),但对我来说没有任何改变,无论我做什么,反斜杠都会保留,最多只会插入\t
或空格。我还读到说我必须将其转换为字节数组,但这对我也没有起作用(也许我在这里做错了什么)。
以下是我的当前代码:
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"`
}
英文:
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"`
}
答案1
得分: 1
两件事情:
- "反斜杠"只是转义字符,它们并不是字面上的存在。
- 对JSON进行缩进只需要调用适当的缩进函数:
如果你已经有了JSON字符串,可以使用encoding/json
包中的json.Indent
函数:
input := []byte("[{\"id\":\"e61b3ff8-6cdf-4b23-97a5-a28107c57543\",\"firstname\":\"John\",\"lastname\":\"Doe\",\"email\":\"john@doe.com\",\"username\":\"johndoe\",\"token\":\"19b33c79-32cc-4063-9381-f2b64161ad8a\",\"lastRequest\":null}]")
buf := &bytes.Buffer{}
if err := json.Indent(buf, input, "", "\t"); err != nil {
panic(err)
}
fmt.Println(buf.String())
然而,如果你想直接将数据编组成缩进形式,只需使用MarshalIndent
函数而不是Marshal
:
userJson, err := json.MarshalIndent(testUser, "", "\t")
英文:
Two things:
- The "backslashes" are just escape characters. They aren't literally there.
- Indenting JSON is a simple matter of calling the appropriate Indent function:
If you have the JSON string already, use the json.Indent
function from the encoding/json
package:
input := []byte("[{\"id\":\"e61b3ff8-6cdf-4b23-97a5-a28107c57543\",\"firstname\":\"John\",\"lastname\":\"Doe\",\"email\":\"john@doe.com\",\"username\":\"johndoe\",\"token\":\"19b33c79-32cc-4063-9381-f2b64161ad8a\",\"lastRequest\":null}]")
buf := &bytes.Buffer{}
if err := json.Indent(buf, input, "", "\t"); err != nil {
panic(err)
}
fmt.Println(buf.String())
However, if you're trying to marshal directly into the indented form, just use the MarshalIndent
function intead of Marshal
:
userJson, err := json.MarshalIndent(testUser, "", "\t")
答案2
得分: 0
这将是我在stackoverflow上的第一个答案,希望能帮到你。
Go gin框架提供了一些方便的函数,由于我不知道你使用的是哪个版本的golang和Gin框架,你可以尝试以下代码:
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)
// 如果需要缩进,你可以尝试:
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"`
}
希望对你有帮助!
英文:
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"`
}
答案3
得分: 0
希望这个函数能够帮到你。
import (
"encoding/json"
"strings"
)
func logRequest(log *logrus.Entry, data []byte) {
cp := bytes.NewBuffer([]byte{})
if err := json.Compact(cp, data); err == nil {
log.Info("收到请求:", string(cp.Bytes()))
} else {
stringifiedData := strings.Replace(string(data[:]), "\n", "", -1)
stringifiedData = strings.Replace(stringifiedData, "\r\n", "", -1)
stringifiedData = strings.Replace(stringifiedData, "\t", "", -1)
log.Info("收到请求:", strings.ReplaceAll(stringifiedData, " ", ""))
}
}
以上是要翻译的内容。
英文:
Hope this function helps.
import (
"encoding/json"
"strings"
)
func logRequest(log *logrus.Entry, data []byte) {
cp := bytes.NewBuffer([]byte{})
if err := json.Compact(cp, data); err == nil {
log.Info("Request received: ", string(cp.Bytes()))
} else {
stringifiedData := strings.Replace(string(data[:]), "\n", "", -1)
stringifiedData = strings.Replace(stringifiedData, "\r\n", "", -1)
stringifiedData = strings.Replace(stringifiedData, "\t", "", -1)
log.Info("Request received: ", strings.ReplaceAll(stringifiedData, " ", ""))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论