json - VBA 解析 JSON 数据

标签 json excel vba

我正在尝试解析来自网站的 JSON 数据。我成功获取了 JSON 字符串,但我无法解析它。下面的代码中抛出了异常:

Runtime Error 424. Object Required



这是我的代码:
' Download string from URL
Public Function DownloadDataFromURL(url As String) As String
    Set Myrequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    Myrequest.Open "GET", url
    Myrequest.send
    Dim WebResponse As String
    WebResponse = Myrequest.responseText
    Cells(1, 1).Value = WebResponse
    DownloadDataFromURL = WebResponse
End Function

' Download all cryptocoins in
Public Sub LoadCryptocoins()
    Dim Path As String
    Dim Data As String
    Dim json As Object

    Path = "https://api.coinmarketcap.com/v1/ticker/"
    Data = DownloadDataFromURL(Path)

    Set jp = New JsonParser
    Set jo = jp.Decode(Data)

    For Each Item In jp.EnumKeys(jo)
        MsgBox (Item.GetValue(jo, "id")) 'The exception is thrown here
    Next
End Sub

我从这里使用 JSON 解析器:Parsing JSON in Excel VBA

我处理的原始 JSON 数据可以在这里找到:https://api.coinmarketcap.com/v1/ticker/

我怎样才能得到每个硬币的名称和美元的价格?

最佳答案

试试下面的脚本。它将获取您提到的所有数据。不需要外部解析器来实现这一点:

Sub coinmarketcap_data()
    Dim http As New XMLHTTP60, res As Variant

    With http
        .Open "GET", "https://api.coinmarketcap.com/v1/ticker/", False
        .send
        res = .responseText
    End With

    For r = 1 To UBound(Split(res, "id"": """))
        Cells(r, 1) = Split(Split(Split(res, "name"": """)(r), """symbol")(0), """")(0)
        Cells(r, 2) = Split(Split(Split(res, "price_usd"": """)(r), """price_btc")(0), """")(0)
    Next r
End Sub

添加到库的引用:
Microsoft XML, v6.0

关于json - VBA 解析 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48084499/

相关文章:

python win32 excel复制工作表并更改复制工作表的名称

vba - 当选择整行时,为什么 Selection.EntireColumn.Address 返回行引用?

excel - 从 VBA 中的函数中选择单元格

javascript - 获取本地 JSON

java - 如何解析jsonarray方括号内容

c# - 有没有办法在 Json.Net JsonSerializer 中使用自定义缩进字符?

python - openpyxl 合并单元格 : Formatting issue

python - 如何使用多个字典转换字符串,以便 json.load 可以解析它?

java - 使用 Apache-POI 编写工作簿后出现问题

vba - Excel VBA 从文件夹中的文件更新主列表