Public Sub Extract_Leaderboard_Data()
Dim httpReq As Object
Dim URL As String
Dim JSONall As Variant
Dim parseState As String
Dim destCell As Range
Dim i As Long
Dim player As Variant
With ThisWorkbook.Worksheets("Leaderboard")
.Cells.Clear
.Range("A1:F1").Value = Array("Pos", "U/D", "Player", "Total", "Hole", "Round")
Set destCell = .Range("A2")
End With
URL = "https://statdata.pgatour.com/r/014/leaderboard-v2mini.json"
Set JSONall = Nothing
Set httpReq = CreateObject("MSXML2.XMLHTTP")
With httpReq
.Open "GET", URL, False
.Send
If .Status = 200 Then
'Debug.Print .responseText
Parse .responseText, JSONall, parseState
If parseState = "Error" Then
MsgBox "Error parsing JSON data"
Exit Sub
End If
End If
End With
With ThisWorkbook.Worksheets("JSON")
If IsEmpty(.Range("A1").Value) Then
.Cells.Clear
JSONToCells JSONall, .Range("A1")
End If
End With
destCell.Worksheet.Range("G1").Value = "Data last updated " & Right(JSONall("last_updated"), 8)
For i = 0 To 19
Set player = JSONall("leaderboard")("players")(i)
destCell.Offset(i, 0).Value = CvtPos(player("current_position"))
destCell.Offset(i, 1).Value = CvtPos(player("start_position")) - CvtPos(player("current_position"))
destCell.Offset(i, 2).Value = player("player_bio")("first_name") & " " & player("player_bio")("last_name")
destCell.Offset(i, 3).Value = player("total")
destCell.Offset(i, 4).Value = player("thru")
destCell.Offset(i, 5).Value = player("today")
Next
End Sub
Private Function CvtPos(ByVal pos As String) As Integer
'Convert position string (which may be prefixed with "T" for 'tied') to its numeric value
If Val(pos) = 0 Then
CvtPos = Mid(pos, 2)
Else
CvtPos = pos
End If
End Function
Private Function JSONToCells(JSONvar As Variant, destCell As Range, Optional ByVal path As String) As Long
Dim n As Long
Dim key As Variant
Dim i As Long
'Output parsed JSON data to Excel cells in a hierarchical layout
n = 0
If varType(JSONvar) = vbObject Then 'Dictionary
For Each key In JSONvar.keys
'Debug.Print key
destCell.Offset(n, 0).Value = key
n = n + JSONToCells(JSONvar.item(key), destCell.Offset(n, 1), path & "(" & key & ")")
Next
ElseIf varType(JSONvar) >= vbArray Then 'Variant()
For i = 0 To UBound(JSONvar)
'Debug.Print i
destCell.Offset(n, 0).Value = i
n = n + JSONToCells(JSONvar(i), destCell.Offset(n, 1), path & "(" & i & ")")
Next
Else
'Debug.Print JSONvar
destCell.Offset(n, 0).Value = JSONvar
CreateComment destCell.Offset(n, 0), path
n = n + 1
End If
JSONToCells = n
End Function
Private Sub CreateComment(cell As Range, commentText As String)
With cell
If .Comment Is Nothing Then .AddComment
.Comment.Visible = False
.Comment.Text Text:=commentText
.Comment.Shape.TextFrame.AutoSize = True
End With
End Sub