我有以下json数组,您可以通过以下网址轻松访问:
https://crowdfluttr.firebaseio.com/test/array.json
它有以下输出:
{"-0p":{"date":"2015-01-01","string":"apple","value":1},"-1p":{"date":"2015-02-04","string":"banana","value":50},"-2p":{"date":"2015-02-03","string":"carrot","value":99},"-3p":{"date":"2015-02-02","string":"banana","value":20},"-4p":{"date":"2015-03-01","string":"banana","value":11},"-5p":{"date":"2015-04-01","string":"kiwi","value":23},"-6p":{"date":"2015-05-01","strawberry":"banana","value":10}}
我想从此网址中提取此json数据,然后解析它以进入微软访问。
我找到了解释如何解析JSON(Parsing JSON,Parsing JSON in Excel VBA)的资源,但是没有从URL中提取它,然后是parseit
答案 0 :(得分:4)
我会使用XMLHTTP下载JSON。
要使用VBA解析JSON,请参阅https://github.com/VBA-tools/VBA-JSON。
下载ZIP文件。提取JsonConverter.bas
。使用您的VBA项目打开Excel和VBA编辑器。右键单击Project Explorer中的VBA项目,然后单击Import File....
浏览到JsonConverter.bas
文件并导入它。请确保您已包含对" Microsoft Scripting Runtime"的引用。通过Tools-References
。
使用您的网址的示例:
Sub test()
Dim httpObject As Object
Set httpObject = CreateObject("MSXML2.XMLHTTP")
sURL = "https://crowdfluttr.firebaseio.com/test/array.json"
sRequest = sURL
httpObject.Open "GET", sRequest, False
httpObject.send
sGetResult = httpObject.responseText
MsgBox sGetResult
Dim oJSON As Object
Set oJSON = JsonConverter.ParseJson(sGetResult)
For Each sItem In oJSON
dItemDate = oJSON(sItem)("date")
sItemString = oJSON(sItem)("string")
vItemValue = oJSON(sItem)("value")
MsgBox "Item: " & sItem & " Date: " & dItemDate & " String: " & sItemString & " Value: " & vItemValue
Next
End Sub
此代码适用于您的样本JSON
,如:
{"-0p":{"date":"2015-01-01","string":"apple","value":1},"-1p":{"date":"2015-02-04","string":"banana","value":50}, ... }
您必须分析从JSON
获得的httpObject.responseText
,以调整代码以获取其他JSON
结构中的值。
答案 1 :(得分:0)
您可以研究答案here,然后查找包含所有必需Json模块的VBA.CVRAPI,以便从URL中检索数据。虽然Json模块是为了其他目的而创建的,但它是通用的,可以很容易地重复使用。
包含的演示表格演示了这一点。您应该能够将其用于您的URL以进行测试。
答案 2 :(得分:0)
以防万一有人偶然发现了这个问题,但是需要先获取参数才能获取responseText
,您需要稍微调整Axel's answer。
httpObject.Open "POST", sURL, False '// instead of GET, use POST //
httpObject.SetRequestHeader "Content-Type", "Application/json" '// specify header //
httpObject.Send "{""param1"":""value1"",""param2"":""value2""}" '// pass parameter //
sGetResult = httpObject.responseText '// get response //
下一步是使用上面提供的功能对结果进行相同的解析。