为了账号安全,请及时绑定邮箱和手机立即绑定

从未封送数据准备 json 对象

从未封送数据准备 json 对象

慕桂英3389331 2022-09-12 16:26:09
我有这样的 json 数据:json: {"opt1":200,"opt3":"1","opt4":"13","opt5":null,"products":[{"product_id":1,"price":100,"variant_id":100},{"product_id":1,"price":100,"variant_id":null}]}我使用type Products struct {    Product_id int    Price json.Number    Variant_id int}type Pdata struct {    Products []Products `json:"products"`}然后我使用解封jsonb := []byte(jsonVal)    var data Pdata    err := json.Unmarshal(jsonb, &data)    if err != nil {        fmt.Println(err)        return    }并获得输出,如{[{1 100 100} {2 100 0}]}现在我需要将这些数据转换为如下所示的json对象{"purchased_products": [{"product_id": 1,"price": 1200,"variation_id": 100},{"product_id": 2,"price": 100,"variation_id": null}]}之后,我需要将其分配给“json”var d = map[string]string{    "json":        jsonVal,    "created_at":  time.Now().Format("2006-01-02 15:04:05"),    "updated_at":  time.Now().Format("2006-01-02 15:04:05"),}我该怎么做?
查看完整描述

4 回答

?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

创建一个类型(例如:购买的产品),如下所示。


type PurchasedProducts struct {

    Products []Products `json:"purchased_products"`

}

初始化“已购买产品”类型变量,并将未密封的产品分配给“已购买的产品”,如下所示。


    pProducts := PurchasedProducts{Products: data.Products}

    jsonByte, err := json.Marshal(pProducts)

    if err != nil {

        fmt.Println(err)

        return

    }

然后将该数组转换为字符串,并将其分配给地图,如下所示。[]byte


    var d = map[string]string{

        "json":        string(jsonByte),

        "created_at":  time.Now().Format("2006-01-02 15:04:05"),

        "updated_at":  time.Now().Format("2006-01-02 15:04:05"),

    }

您可以在此处运行并查看完整代码。


查看完整回答
反对 回复 2022-09-12
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

只需再定义两个结构来模拟第二个 JSON 对象:


type Pdata2 struct {

    PurchasedProducts []Product2

}


type Product2 struct {

    Product_id    int

    Price         json.Number

    Variation_id  *int // pointer to int

}

该字段是一种类型,因为所需的输出 JSON 显示 。如果将字段声明为简单字段,则其零值将被封送至 。Variation_id*int"variation_id": nullint0


然后使用前面结构中的值初始化这些结构:


func main() {

    data2 := Pdata2{

        PurchasedProducts: make([]Product2, len(data.Products)),

    }


    for i, p := range data.Products {

        data2.PurchasedProducts[i] = Product2{

            Product_id:   p.Product_id,

            Price:        p.Price,

            Variation_id: nullableInt(p.Variant_id),

        }

    }


    b, err := json.Marshal(data2)

    if err != nil {

        // ... handle error

    }

    var d = map[string]string{

        "json": string(b),

        // ...

    }

    fmt.Println(d)

}


func nullableInt(n int) *int {

    if n == 0 {

        return nil

    }

    return &n

}


游乐场: https://play.golang.org/p/xhsmHNBjRKN


查看完整回答
反对 回复 2022-09-12
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

对于可为 null 的字段,您可以使用指针,例如,如果 json 字段可以是整数或 json ,并且您希望保留该信息,则可以更改为 。variant_idnullVariant_id intVariant_id *int


type Product struct {

    Product_id int         `json:"product_id"`

    Price      json.Number `json:"price"`

    Variant_id *int        `json:"variant_id"`

}

要在取消封送和封送之间更改 json 字段名称,您可以声明第二个结构,其字段与原始字段相同,但具有定义所需字段名称的结构标记,那么,如果结构在所有其他方面等效,则可以在它们之间进行转换。Products


type Product struct {

    Product_id int         `json:"product_id"`

    Price      json.Number `json:"price"`

    Variant_id int         `json:"variant_id"`

}


type PurchasedProduct struct {

    Product_id int         `json:"product_id"`

    Price      json.Number `json:"price"`

    Variant_id int         `json:"variation_id"` // here variant_id becomes variation_id

}

然后,如果 是 类型 ,您可以简单地将其转换为如下所示:pProductPurchasedProduct


pp := PurchasedProduct(p)

要将转换卸载到封送处理过程,可以让原始类型实现接口并在那里执行转换。json.Marshaler


func (p Product) MarshalJSON() ([]byte, error) {

    type P struct {

        Product_id int         `json:"product_id"`

        Price      json.Number `json:"price"`

        Variant_id *int        `json:"variation_id"`

    }

    return json.Marshal(P(p))

}

通过上述操作,您可以执行以下操作:


func main() {

    // unmarshal

    var pd Pdata

    err := json.Unmarshal(data, &pd)

    if err != nil {

        panic(err)

    }


    // marshal

    out, err := json.MarshalIndent(pd, "", "  ")

    if err != nil {

        panic(err)

    }

    fmt.Println(string(out))

}

https://play.golang.org/p/0gnrjgUslza


查看完整回答
反对 回复 2022-09-12
?
当年话下

TA贡献1890条经验 获得超9个赞

给你。假设是:

  • 产品是一个可能更复杂的模型,因此它具有专用的结构。因此,从产品到输出产品的转换可以单独进行单元测试。

  • 它是一次性使用应用程序,而不是公开 API 的应用程序的一部分。否则,应将其适当地分成几层,并将输出编写为结构。

package main


import (

    "encoding/json"

    "log"

    "os"

    "time"

)


type (

    Product struct {

        ProductID int `json:"product_id"`

        VariantID int `json:"variant_id"`

        Price     json.Number

    }

    Products []Product


    OutputProduct struct {

        ProductID int `json:"product_id"`

        VariantID int `json:"variation_id"`

        Price     json.Number

    }

)


func (p Product) ToOutputProduct() OutputProduct {

    return OutputProduct{

        ProductID: p.ProductID,

        VariantID: p.VariantID,

        Price:     p.Price,

    }

}


func (p Products) ToOutputProducts() []OutputProduct {

    outputProducts := make([]OutputProduct, len(p))

    for i := 0; i < len(p); i++ {

        outputProducts[i] = p[i].ToOutputProduct()

    }

    return outputProducts

}


func main() {

    var inputJSON = `{"opt1":200,"opt3":"1","opt4":"13","opt5":null,"products":[{"product_id":1,"price":100,"variant_id":100},{"product_id":1,"price":100,"variant_id":null}]}`


    var parsedInput struct {

        Products Products

    }

    if err := json.Unmarshal([]byte(inputJSON), &parsedInput); err != nil {

        log.Fatal(err)

    }


    var output = map[string]interface{}{

        "json":       map[string][]OutputProduct{

            "purchased_products": parsedInput.Products.ToOutputProducts(),

        },

        "created_at": time.Now().Format("2006-01-02 15:04:05"),

        "updated_at": time.Now().Format("2006-01-02 15:04:05"),

    }

    encoder := json.NewEncoder(os.Stdout)

    encoder.SetIndent(" ", "  ")

    if err := encoder.Encode(output); err != nil {

        log.Fatal(err)

    }

}


查看完整回答
反对 回复 2022-09-12
  • 4 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号