如何在Golang中为JSON字符串添加前缀

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

how to add prefix json string in golang

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是新手。我在我的数据库中有一个image,它以路径的形式存储。在API的JSON中,我需要输出这个路径,并在其前面添加一个prefix,我该如何做呢?

我的函数:

func GetAllSliders(c *gin.Context) {
    var sliders models.Slider

    config.DB.Model(models.Slider{}).Where("id=?", 1).Update("image", ("https://spares-dt.ru/" + models.Slider{}.Image)) //我尝试了这个,但它不起作用

    if err := config.DB.Find(&sliders).Error; err != nil {
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        c.JSON(http.StatusOK, gin.H{"data": sliders})
    }
}

我有的JSON输出:

{
    "data": {
        "id": 1,
        "main_text": "123",
        "upper_text": "123",
        "down_text": "123",
        "image": "data/photos/sliders/image.PNG"
    }
}

我想要的输出:

{
    "data": {
        "id": 1,
        "main_text": "123",
        "upper_text": "123",
        "down_text": "123",
        "image": "https://spakes-dt.ru/data/photos/sliders/image.PNG"
    }
}

我的结构体:

type Slider struct {
    Id        uint   `json:"id" gorm:"primaryKey"`
    MainText  string `json:"main_text"`
    UpperText string `json:"upper_text"`
    DownText  string `json:"down_text"`
    Image     string `json:"image"`
}
英文:

I am newbie. I have a image in my db which is stored as a path to it. In api json I have to output this path and add a prefix in front of it, how can I do that?
My function:

func GetAllSliders(c *gin.Context) {
	var sliders models.Slider

	config.DB.Model(models.Slider{}).Where("id=?", 1).Update("image", ("https://spares-dt.ru/" + models.Slider{}.Image)) //i tried this, but it doesnt work

	if err := config.DB.Find(&sliders).Error; err != nil {
		c.JSON(http.StatusInternalServerError, err.Error())
	} else {
		c.JSON(http.StatusOK, gin.H{"data": sliders})
	}
}

Json output i have:

{
    "data": {
        "id": 1,
        "main_text": "123",
        "upper_text": "123",
        "down_text": "123",
        "image": "data/photos/sliders/image.PNG"
    }
}

I want:

{
    "data": {
        "id": 1,
        "main_text": "123",
        "upper_text": "123",
        "down_text": "123",
        "image": "https://spakes-dt.ru/data/photos/sliders/image.PNG"
    }
}

And my struct:

type Slider struct {
	Id        uint   `json:"id" gorm:"primaryKey"`
	MainText  string `json:"main_text"`
	UpperText string `json:"upper_text"`
	DownText  string `json:"down_text"`
	Image     string `json:"image"`
}

答案1

得分: 1

在JSON编组之前,只需更改Image字段的值:

if err := config.DB.Find(&sliders).Error; err != nil {
    c.JSON(http.StatusInternalServerError, err.Error())
} else {
    sliders.Image = "https://spares-dt.ru/" + sliders.Image
    c.JSON(http.StatusOK, gin.H{"data": sliders})
}

在对sliders进行JSON编组之前,将Image字段的值修改为"https://spares-dt.ru/" + sliders.Image

英文:

Simply change the Image field's value before JSON marshaling it:

if err := config.DB.Find(&sliders).Error; err != nil {
    c.JSON(http.StatusInternalServerError, err.Error())
} else {
    sliders.Image = "https://spares-dt.ru/" + sliders.Image
    c.JSON(http.StatusOK, gin.H{"data": sliders})
}

答案2

得分: 0

这是一个自定义JSON编组的示例。通过添加MarshalJson方法来修改您的模型,可以帮助您进行自定义。

package main

import (
	"encoding/json"
	"fmt"
)

type Slider struct {
	ID        int    `json:"id"`
	MainText  string `json:"main_text"`
	UpperText string `json:"upper_text"`
	DownText  string `json:"down_text"`
	Image     string `json:"image"`
}

// 添加MarshalJson方法
func (u *Slider) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		ID        int    `json:"id"`
		MainText  string `json:"main_text"`
		UpperText string `json:"upper_text"`
		DownText  string `json:"down_text"`
		Image     string `json:"image"`
	}{
		ID:        u.ID,
		MainText:  u.MainText,
		UpperText: u.UpperText,
		DownText:  u.DownText,
		Image:     "https://spakes-dt.ru/" + u.Image,
	})
}

func main() {
	data := Slider{Image: "data/photos/sliders/image.PNG"}
	bdata, _ := json.Marshal(data)
	fmt.Println(string(bdata))
}

这将产生以下输出。

{
  "id": 0,
  "main_text": "",
  "upper_text": "",
  "down_text": "",
  "image": "data/photos/sliders/image.PNG"
}

在创建MarshalJson方法后,更新您的代码如下所示。

func GetAllSliders(c *gin.Context) {
    var sliders models.Slider

    config.DB.Model(models.Slider{}).Where("id=?", 1)//我尝试了这个,但它不起作用

    if err := config.DB.Find(&sliders).Error; err != nil {
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        b, _  := json.Marshal(sliders)
        c.JSON(http.StatusOK, gin.H{"data": string(b)})
    }
}
英文:

This is an example of how custom json marshalling works. Modifying your model by adding the MarshalJson method will help you to customize.

package main

import (
	"encoding/json"
	"fmt"
)

type Slider struct {
	ID        int    `json:"id"`
	MainText  string `json:"main_text"`
	UpperText string `json:"upper_text"`
	DownText  string `json:"down_text"`
	Image     string `json:"image"`
}

//Add MarshalJson function
func (u *Slider) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		ID        int    `json:"id"`
		MainText  string `json:"main_text"`
		UpperText string `json:"upper_text"`
		DownText  string `json:"down_text"`
		Image     string `json:"image"`
	}{
		ID:        u.ID,
		MainText:  u.MainText,
		UpperText: u.UpperText,
		DownText:  u.DownText,
		Image:     "https://spakes-dt.ru/" + u.Image,
	})
}

func main() {
	data := Slider{Image: "data/photos/sliders/image.PNG"}
	bdata, _ := json.Marshal(data)
	fmt.Println(string(bdata))
}

This will produce the following output.

{
  "id": 0,
  "main_text": "",
  "upper_text": "",
  "down_text": "",
  "image": "data/photos/sliders/image.PNG"
}

Update your code something like this after you create MarshalJson method

func GetAllSliders(c *gin.Context) {
    var sliders models.Slider

    config.DB.Model(models.Slider{}).Where("id=?", 1)//i tried this, but it doesnt work

    if err := config.DB.Find(&sliders).Error; err != nil {
        c.JSON(http.StatusInternalServerError, err.Error())
    } else {
        b, _  := json.Marshal(sliders)
        c.JSON(http.StatusOK, gin.H{"data": string(b)})
    }
}

答案3

得分: 0

你应该使用exec函数:

config.DB.Exec(`UPDATE slider SET image = "https://spares-dt.ru/" + image WHERE id = ?`, 1)
英文:

you should use exec

config.DB.Exec(`UPDATE slider SET image = "https://spares-dt.ru/" + iamge WHERE id = ?`, 1)

huangapple
  • 本文由 发表于 2022年8月3日 17:13:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73219156.html
匿名

发表评论

匿名网友

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

确定