TutorialEdge

Challenge 21 - JSON and Stock Dividends

Welcome, everyone to the discussion thread for the 21st Go challenge posted to the site :tada:

Feel free to show us how you solved the challenge by posting your solutions below!

package main

import (
    "encoding/json"
    "fmt" 
)

type Stocks struct {
  Stocks []Stocks
}

type Stock struct {
  Ticker   string 	`json:"ticker"`
  Dividend float64    `json:'dividend"`
}

// HighestDividend iterates through a JSON string of stocks
// unmarshalls them into a struct and returns the Stock with
// the highest dividend
func HighestDividend(str string) string {
  var ticker []Stock
  
  if err := json.Unmarshal([]byte(str), &ticker); err != nil {
    panic(err)
    return ""
  }
  
  if len(ticker) == 0 {
    return ""
  }
  
  highest := ticker[0]
  for _, v:= range ticker {
    if highest.Dividend < v.Dividend {
     	highest = v 
    }
  }
  
  return highest.Ticker
}

func main() {
  fmt.Println("Stock Price AI")

  stocks_json := `[
    {"ticker":"APPL","dividend":0.5},
    {"ticker":"GOOG","dividend":0.2},
    {"ticker":"MSFT","dividend":0.3},
    {"ticker":"MSFX","dividend":3}
  ]`

  highestDividend := HighestDividend(stocks_json)
  fmt.Println(highestDividend)
}
1 Like

Awesome!

I just realised I haven’t yet added the solution to this challenge myself so fair play for beating me to it! :muscle: