I am trying to get my json to be formatted in a particular way to be inserted into a database. I am able to unmarshal the json and map it to a struct just fine but I need to be able to add and remove attributes for the Companies array that I need. How can I get it to produce the end result noted in the code below?
package main
import (
"encoding/json"
"fmt"
)
type InterestedParties struct {
Companies []Company `json:"companies"`
CCID string `json:"eventCCID"`
}
type Company struct {
CompanyID string `json:"companyID"`
CompanyType string `json:"companyType"`
WebAPI string `json:"webAPI"`
}
type Entitlement struct {
Long string
Voteable string
Tabulation string
Confirm string
}
func main() {
intPartiesJSON := `{"companies": [{"companyID":"COMP0001","companyType":"1","webAPI":"http://google.com"}, {"companyID":"COMP0002","companyType":"1","webAPI":"http://google.com"}],"eventCCID":"laksjlijivelnsvnklsnvlsv"}`
var intParties InterestedParties
err := json.Unmarshal([]byte(intPartiesJSON), &intParties)
if err != nil {
fmt.Println("Error while unmarshalling")
return
}
fmt.Println(intParties)
b, _ := json.Marshal(intParties)
fmt.Println(string(b))
**EDIT:**
//This is how I want the marshalled data to look
//endResult := `[{"companyID": "COMP001", "entitlements":{"long":"","voteable":"", "tabulation":"","confirm":""}, "effective_date": "2017-01-01"},{"companyID": "COMP002", "entitlements":{"long":"","voteable":"", "tabulation":"","confirm":""}, "effective_date": "2017-01-01"}]`
b, _ := json.Marshal(map[string]interface{}{
"companyID": intParties.Companies[0].CompanyID,
"entitlements": Entitlement{},
"effective_date": "2017-01-01",
})
You can create new struct and add the attribute as you wanted for the endResult
for example :
//endResult := `{"companyID": "COMP001", "entitlements":{"long":"","voteable":"", "tabulation":"","confirm":""}, "effective_date": "2017-01-01"}`
The end result have companyID
,entitlements
, and effective_date
your new struct will look like this :
type NewStruct struct {
CompanyID string
Entitlements Entitlement
EffectiveDate string
}
You can also add use []interface{}
if you wanted to add some dynamic attribute :
// or you can add new attribute using interface{}
type NewStruct2 struct {
CompanyID string
Entitlements Entitlement
EffectiveDate string
NewAttribute []interface{}
}
and call it using :
entitlement := Entitlement{Long: "check it out", Confirm: "yes"}
newStruct := NewStruct{CompanyID: "1234"}
endResult := NewStruct2{CompanyID: "222", Entitlements: entitlement}
endResult2 := NewStruct2{CompanyID: "222", Entitlements: entitlement}
fmt.Printf("result = %+v
", endResult)
fmt.Printf("result = %+v
", endResult2)
// we can add any value or struct to NewAttribute here.
endResult.NewAttribute = append(endResult.NewAttribute, newStruct)
endResult.NewAttribute = append(endResult.NewAttribute, endResult2)
fmt.Printf("endResult = %+v
", endResult)