How I can write the value of mongo objectid in json string in golang

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

How I can write the value of mongo objectid in json string in golang

问题

objectid始终是唯一且不可预测的。我希望这个变量应该取primitive.NewObjectID.Hex()的值。

  1. var mockData = `{"status":201,"message":"用户创建成功!","data":{"data":"{"InsertedID":primitive.NewObjectID().Hex()}"}}`

但是像这样写会使输出变成一个普通的字符串。

英文:

The objectid is always unique and unpredictable. I want that, this var should take value of primitive.NewObjectID.Hex()

  1. var mockData = `{"status":201,"message":"User Created Successfully!","data":{"data":"{"InsertedID":primitive.NewObjectID().Hex()}"}}`

But writing it like this gives me a straight string in output.

答案1

得分: 1

你需要“打破”字符串字面量,并使用+进行连接:

  1. var mockData = `{"status":201,"message":"User Created Successfully!","data":{"data":{"InsertedID":"` + primitive.NewObjectID().Hex() + `"}}}`

这样做是可行的,因为十六进制对象ID在JSON中不需要特殊转义,但通常情况下,你应该使用encoding/json包生成有效的JSON(它知道正确的转义方式)。

使用encoding/json包,代码可能如下所示:

  1. var s struct {
  2. Status int `json:"status"`
  3. Message string `json:"message"`
  4. Data struct {
  5. Data struct {
  6. InsertedID string
  7. } `json:"data"`
  8. } `json:"data"`
  9. }
  10. s.Status = 201
  11. s.Message = "User Created Successfully!"
  12. s.Data.Data.InsertedID = primitive.NewObjectID().Hex()
  13. out, err := json.Marshal(s)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(string(out))

你可以在Go Playground上尝试这些示例。

英文:

You have to "break" the string literal and concatenate the parts using +:

  1. var mockData = `{"status":201,"message":"User Created Successfully!","data":{"data":{"InsertedID":"` + primitive.NewObjectID().Hex() + `"}}}`

This will work because the hex object ID does not need any special escaping in JSON, but in general you should use the encoding/json package to generate valid JSON (which knows about proper escaping).

Using the encoding/json package this is how it could look like:

  1. var s struct {
  2. Status int `json:"status"`
  3. Message string `json:"message"`
  4. Data struct {
  5. Data struct {
  6. InsertedID string
  7. } `json:"data"`
  8. } `json:"data"`
  9. }
  10. s.Status = 201
  11. s.Message = "User Created Successfully!"
  12. s.Data.Data.InsertedID = primitive.NewObjectID().Hex()
  13. out, err := json.Marshal(s)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(string(out))

Try the examples on the Go Playground.

huangapple
  • 本文由 发表于 2022年2月3日 19:54:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70970825.html
匿名

发表评论

匿名网友

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

确定