jsongoencoding-json-go

Prepare a json object from unmarshaled data


I have json data like this:

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}]}

I have structured it using

type Products struct {
    Product_id int
    Price json.Number
    Variant_id int
}


type Pdata struct {
    Products []Products `json:"products"`
}

Then I use unmarshal

jsonb := []byte(jsonVal)
    var data Pdata
    err := json.Unmarshal(jsonb, &data)
    if err != nil {
        fmt.Println(err)
        return
    }

And get output like

{[{1 100 100} {2 100 0}]}

Now I need to convert that data into a json object like this

{"purchased_products": [{"product_id": 1,"price": 1200,"variation_id": 100},{"product_id": 2,"price": 100,"variation_id": null}]}

After that, I need to assign it to "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"),
}

How can I do it?


Solution

  • Create a type (eg : PurchasedProducts) as below.

    type PurchasedProducts struct {
        Products []Products `json:"purchased_products"`
    }
    

    And init a PurchasedProducts type variable and assign your unmarshaled products to Purchased products as below.

        pProducts := PurchasedProducts{Products: data.Products}
        jsonByte, err := json.Marshal(pProducts)
        if err != nil {
            fmt.Println(err)
            return
        }
    

    And convert that []byte array to a string and assign it to the map like below.

        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"),
        }
    

    You can run and see full code here.