Created
July 24, 2023 04:30
-
-
Save RyosukeCla/e9c86a2f79d728ed18b071c8faa23f23 to your computer and use it in GitHub Desktop.
convert saleforce_report_response to csv.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/csv" | |
"encoding/json" | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
type SalesforceReturnValue struct { | |
FactMap struct { | |
TT struct { | |
Aggregates []struct { | |
Label string `json:"label"` | |
Value interface{} `json:"value"` | |
} `json:"aggregates"` | |
Rows []struct { | |
DataCells []struct { | |
Label string `json:"label"` | |
Value interface{} `json:"value"` | |
} `json:"dataCells"` | |
} `json:"rows"` | |
} `json:"T!T"` | |
} `json:"factMap"` | |
} | |
type SalesforceAction struct { | |
Id string `json:"id"` | |
State string `json:"state"` | |
ReturnValue map[string]interface{} `json:"returnValue"` | |
} | |
type SalesforceReport struct { | |
Actions []SalesforceAction `json:"actions"` | |
} | |
func main() { | |
err := convertToCsv("billing.json", "billing.csv") | |
if err != nil { | |
panic(err) | |
} | |
err = convertToCsv("details.json", "details.csv") | |
if err != nil { | |
panic(err) | |
} | |
} | |
func convertToCsv(sfJsonFilepath string, writeFilepath string) error { | |
billingJsonFile, err := os.Open(sfJsonFilepath) | |
if err != nil { | |
return err | |
} | |
defer billingJsonFile.Close() | |
billingJson, err := io.ReadAll(billingJsonFile) | |
if err != nil { | |
return err | |
} | |
billing := &SalesforceReport{} | |
err = json.Unmarshal(billingJson, billing) | |
if err != nil { | |
return err | |
} | |
file, _ := os.Create(writeFilepath) | |
defer file.Close() | |
csvWriter := csv.NewWriter(file) | |
csvWriter.Comma = '\t' | |
var rawReturnValue map[string]interface{} | |
for _, action := range billing.Actions { | |
if action.ReturnValue["factMap"] != nil { | |
rawReturnValue = action.ReturnValue | |
break | |
} | |
} | |
if rawReturnValue == nil { | |
return fmt.Errorf("no factMap found in %s", sfJsonFilepath) | |
} | |
sfReturnValue := &SalesforceReturnValue{} | |
err = mapToStruct(rawReturnValue, &sfReturnValue) | |
if err != nil { | |
return err | |
} | |
for _, row := range sfReturnValue.FactMap.TT.Rows { | |
csvRow := []string{} | |
for _, cell := range row.DataCells { | |
csvRow = append(csvRow, strings.Replace(cell.Label, "¥", "", 1)) | |
} | |
csvWriter.Write(csvRow) | |
} | |
csvWriter.Flush() | |
return nil | |
} | |
func mapToStruct(mapData map[string]interface{}, data interface{}) error { | |
jsonData, _ := json.Marshal(mapData) | |
return json.Unmarshal(jsonData, data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment