Created
April 1, 2018 02:24
-
-
Save jvmvik/42dc1861f4644cd7a3d5b956bc9d1313 to your computer and use it in GitHub Desktop.
Unmarshalling nested JSON / Hash with dynamic key
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" | |
| "fmt" | |
| "io/ioutil" | |
| "log" | |
| "os" | |
| ) | |
| type Stock struct { | |
| Symbol string `json:"symbol"` | |
| Title string `json:"title"` | |
| Share int `json:"share"` | |
| PurchasePrice float64 `json:"purchase_price"` | |
| TargetPrice float64 `json:"target_price"` | |
| } | |
| type Account map[string]Stock | |
| func main() { | |
| raw, err := ioutil.ReadFile("stock.json") | |
| if err != nil { | |
| fmt.Println(err.Error()) | |
| os.Exit(1) | |
| } | |
| var account Account | |
| json.Unmarshal(raw, &account) | |
| log.Println(account) | |
| } |
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
| { | |
| "MU": { | |
| "symbol": "MU", | |
| "title": "micro semiconductor", | |
| "share": 400, | |
| "purchase_price": 60.5, | |
| "target_price": 70 | |
| }, | |
| "LSCC":{ | |
| "symbol": "LSCC", | |
| "title": "lattice semiconductor", | |
| "share": 200, | |
| "purchase_price": 20, | |
| "target_price": 30 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment