Created
September 24, 2020 19:33
-
-
Save ryanc414/8ecac2294c4c02a73ef4c1c1cb98f6d7 to your computer and use it in GitHub Desktop.
Process a JSON file, in Go
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/json" | |
"errors" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"os" | |
) | |
type cmdlineArgs struct { | |
sourcePath string | |
destPath string | |
userID string | |
} | |
type transaction struct { | |
From string `json:"from"` | |
To string `json:"to"` | |
Amount json.Number `json:"amount"` | |
} | |
func main() { | |
args := parse_args() | |
if err := processJSON(args); err != nil { | |
fmt.Println("error filtering transactions:", err.Error()) | |
os.Exit(1) | |
} | |
fmt.Println("filtered transactions written to", args.destPath) | |
} | |
func processJSON(args *cmdlineArgs) error { | |
if args.userID == "" { | |
return errors.New("-user-id argument is required") | |
} | |
filecontent, err := ioutil.ReadFile(args.sourcePath) | |
if err != nil { | |
return err | |
} | |
var transactions []transaction | |
if err := json.Unmarshal(filecontent, &transactions); err != nil { | |
return err | |
} | |
filteredTransactions := filterTransactions(transactions, args.userID) | |
filteredTransData, err := json.Marshal(filteredTransactions) | |
if err != nil { | |
return err | |
} | |
return ioutil.WriteFile(args.destPath, filteredTransData, 0644) | |
} | |
func filterTransactions(transactions []transaction, userID string) []transaction { | |
var filteredTransactions []transaction | |
for i := range transactions { | |
if transactions[i].From == userID { | |
filteredTransactions = append(filteredTransactions, transactions[i]) | |
} | |
} | |
return filteredTransactions | |
} | |
func parse_args() *cmdlineArgs { | |
sourcePath := flag.String("source-path", "transactions.json", "path to source JSON file") | |
destPath := flag.String("dest-path", "filtered_transactions.json", "path to output JSON file") | |
userID := flag.String("user-id", "", "user ID to filter on") | |
flag.Parse() | |
return &cmdlineArgs{ | |
sourcePath: *sourcePath, | |
destPath: *destPath, | |
userID: *userID, | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment