在Go中将JSON解组为自定义格式

时间:2017-02-17 20:27:50

标签: json go struct marshalling unmarshalling

我试图让我的json以特定的方式格式化以插入数据库。我能够解组json并将其映射到结构,但我需要能够为我需要的Companies数组添加和删除属性。如何让它产生下面代码中提到的最终结果?

word2

2 个答案:

答案 0 :(得分:0)

b, _ := json.Marshal(map[string]interface{}{
    "companyID":      intParties.Companies[0].CompanyID,
    "entitlements":   Entitlement{},
    "effective_date": "2017-01-01",
})

答案 1 :(得分:0)

您可以根据需要为endResult创建新结构并添加属性,例如:

//endResult := `{"companyID": "COMP001", "entitlements":{"long":"","voteable":"", "tabulation":"","confirm":""}, "effective_date": "2017-01-01"}`

最终结果包含companyIDentitlementseffective_date 你的新结构将如下所示:

type NewStruct struct {
    CompanyID     string
    Entitlements  Entitlement
    EffectiveDate string
}

如果您想添加一些动态属性,还可以添加使用[]interface{}

// or you can add new attribute using interface{}
type NewStruct2 struct {
    CompanyID     string
    Entitlements  Entitlement
    EffectiveDate string
    NewAttribute  []interface{}
}

并使用:

调用它
    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\n", endResult)
    fmt.Printf("result = %+v\n", 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\n", endResult)