dtf1111 2017-02-17 20:27
浏览 39

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

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"}]`
  • 写回答

2条回答 默认 最新

  • dslijian2015 2017-02-17 22:47
    关注
    b, _ := json.Marshal(map[string]interface{}{
        "companyID":      intParties.Companies[0].CompanyID,
        "entitlements":   Entitlement{},
        "effective_date": "2017-01-01",
    })
    
    评论

报告相同问题?