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

huangapple go评论93阅读模式
英文:

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)

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

But I want it like this:

[{
        &quot;id&quot;: &quot;e61b3ff8-6cdf-4b23-97a5-a28107c57543&quot;,
        &quot;username&quot;: &quot;johndoe&quot;,
        &quot;email&quot;: &quot;john@doe.com&quot;,
        &quot;token&quot;: &quot;19b33c79-32cc-4063-9381-f2b64161ad8a&quot;,
        &quot;lastRequest&quot;: 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(&quot;/getusers&quot;, func(c *gin.Context) {
	usersArr := make([]User, len(users))
	for i := 0; i &lt; len(users); i++ {
		usersArr[i] = users[i]
	}
		
	userJson, err := json.Marshal(testUser)
	if err != nil {
		c.JSON(400, gin.H{&quot;error&quot;: err.Error()})
	} else {
		c.JSON(200, string(userJson))
	}
})

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

答案1

得分: 1

两件事情:

  1. "反斜杠"只是转义字符,它们并不是字面上的存在。
  2. 对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())

Playground链接

然而,如果你想直接将数据编组成缩进形式,只需使用MarshalIndent函数而不是Marshal

userJson, err := json.MarshalIndent(testUser, "", "\t")
英文:

Two things:

  1. The "backslashes" are just escape characters. They aren't literally there.
  2. 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(&quot;[{\&quot;id\&quot;:\&quot;e61b3ff8-6cdf-4b23-97a5-a28107c57543\&quot;,\&quot;firstname\&quot;:\&quot;John\&quot;,\&quot;lastname\&quot;:\&quot;Doe\&quot;,\&quot;email\&quot;:\&quot;john@doe.com\&quot;,\&quot;username\&quot;:\&quot;johndoe\&quot;,\&quot;token\&quot;:\&quot;19b33c79-32cc-4063-9381-f2b64161ad8a\&quot;,\&quot;lastRequest\&quot;:null}]&quot;)
buf := &amp;bytes.Buffer{}
if err := json.Indent(buf, input, &quot;&quot;, &quot;\t&quot;); err != nil {
	panic(err)
}
fmt.Println(buf.String())

Playground link

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, &quot;&quot;, &quot;\t&quot;)

答案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(&quot;/getusers&quot;, func(c *gin.Context) {
    usersArr := make([]User, len(users))
    for i := 0; i &lt; len(users); i++ {
        usersArr[i] = users[i]
    }
        
    if err != nil {
        c.JSON(400, gin.H{&quot;error&quot;: err.Error()})
    } else {
        c.JSON(200, users)
// If Indentation is required you could try:
        c.IndentedJSON(200, users)
    }
})

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

答案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 (
&quot;encoding/json&quot;
&quot;strings&quot;
)

func logRequest(log *logrus.Entry, data []byte) {
    	cp := bytes.NewBuffer([]byte{})
    	if err := json.Compact(cp, data); err == nil {
    		log.Info(&quot;Request received: &quot;, string(cp.Bytes()))
    	} else {
    		stringifiedData := strings.Replace(string(data[:]), &quot;\n&quot;, &quot;&quot;, -1)
    		stringifiedData = strings.Replace(stringifiedData, &quot;\r\n&quot;, &quot;&quot;, -1)
    		stringifiedData = strings.Replace(stringifiedData, &quot;\t&quot;, &quot;&quot;, -1)
    		log.Info(&quot;Request received: &quot;, strings.ReplaceAll(stringifiedData, &quot; &quot;, &quot;&quot;))
    	}
    }

huangapple
  • 本文由 发表于 2022年4月18日 15:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/71909020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定