Skip to content

Instantly share code, notes, and snippets.

@jvmvik
Created April 1, 2018 02:24
Show Gist options
  • Select an option

  • Save jvmvik/42dc1861f4644cd7a3d5b956bc9d1313 to your computer and use it in GitHub Desktop.

Select an option

Save jvmvik/42dc1861f4644cd7a3d5b956bc9d1313 to your computer and use it in GitHub Desktop.
Unmarshalling nested JSON / Hash with dynamic key
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)
}
{
"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