猿问

从未封送数据准备 json 对象

我有这样的 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"),

}

我该怎么做?


慕桂英3389331
浏览 131回答 4
4回答

翻翻过去那场雪

创建一个类型(例如:购买的产品),如下所示。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"),    }您可以在此处运行并查看完整代码。

Smart猫小萌

只需再定义两个结构来模拟第二个 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

眼眸繁星

对于可为 null 的字段,您可以使用指针,例如,如果 json 字段可以是整数或 json ,并且您希望保留该信息,则可以更改为 。variant_idnullVariant_id intVariant_id *inttype Product struct {    Product_id int         `json:"product_id"`    Price      json.Number `json:"price"`    Variant_id *int        `json:"variant_id"`}要在取消封送和封送之间更改 json 字段名称,您可以声明第二个结构,其字段与原始字段相同,但具有定义所需字段名称的结构标记,那么,如果结构在所有其他方面等效,则可以在它们之间进行转换。Productstype 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}然后,如果 是 类型 ,您可以简单地将其转换为如下所示:pProductPurchasedProductpp := PurchasedProduct(p)要将转换卸载到封送处理过程,可以让原始类型实现接口并在那里执行转换。json.Marshalerfunc (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

当年话下

给你。假设是:产品是一个可能更复杂的模型,因此它具有专用的结构。因此,从产品到输出产品的转换可以单独进行单元测试。它是一次性使用应用程序,而不是公开 API 的应用程序的一部分。否则,应将其适当地分成几层,并将输出编写为结构。package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "log"&nbsp; &nbsp; "os"&nbsp; &nbsp; "time")type (&nbsp; &nbsp; Product struct {&nbsp; &nbsp; &nbsp; &nbsp; ProductID int `json:"product_id"`&nbsp; &nbsp; &nbsp; &nbsp; VariantID int `json:"variant_id"`&nbsp; &nbsp; &nbsp; &nbsp; Price&nbsp; &nbsp; &nbsp;json.Number&nbsp; &nbsp; }&nbsp; &nbsp; Products []Product&nbsp; &nbsp; OutputProduct struct {&nbsp; &nbsp; &nbsp; &nbsp; ProductID int `json:"product_id"`&nbsp; &nbsp; &nbsp; &nbsp; VariantID int `json:"variation_id"`&nbsp; &nbsp; &nbsp; &nbsp; Price&nbsp; &nbsp; &nbsp;json.Number&nbsp; &nbsp; })func (p Product) ToOutputProduct() OutputProduct {&nbsp; &nbsp; return OutputProduct{&nbsp; &nbsp; &nbsp; &nbsp; ProductID: p.ProductID,&nbsp; &nbsp; &nbsp; &nbsp; VariantID: p.VariantID,&nbsp; &nbsp; &nbsp; &nbsp; Price:&nbsp; &nbsp; &nbsp;p.Price,&nbsp; &nbsp; }}func (p Products) ToOutputProducts() []OutputProduct {&nbsp; &nbsp; outputProducts := make([]OutputProduct, len(p))&nbsp; &nbsp; for i := 0; i < len(p); i++ {&nbsp; &nbsp; &nbsp; &nbsp; outputProducts[i] = p[i].ToOutputProduct()&nbsp; &nbsp; }&nbsp; &nbsp; return outputProducts}func main() {&nbsp; &nbsp; 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}]}`&nbsp; &nbsp; var parsedInput struct {&nbsp; &nbsp; &nbsp; &nbsp; Products Products&nbsp; &nbsp; }&nbsp; &nbsp; if err := json.Unmarshal([]byte(inputJSON), &parsedInput); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; var output = map[string]interface{}{&nbsp; &nbsp; &nbsp; &nbsp; "json":&nbsp; &nbsp; &nbsp; &nbsp;map[string][]OutputProduct{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "purchased_products": parsedInput.Products.ToOutputProducts(),&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; "created_at": time.Now().Format("2006-01-02 15:04:05"),&nbsp; &nbsp; &nbsp; &nbsp; "updated_at": time.Now().Format("2006-01-02 15:04:05"),&nbsp; &nbsp; }&nbsp; &nbsp; encoder := json.NewEncoder(os.Stdout)&nbsp; &nbsp; encoder.SetIndent(" ", "&nbsp; ")&nbsp; &nbsp; if err := encoder.Encode(output); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答