【问题标题】:Amending a json query修改 json 查询
【发布时间】:2018-10-14 13:00:37
【问题描述】:

我需要用excel vba修改一个Json

我希望能够使用 VBA 动态更改邮政编码或将此部分指向工作簿中的单元格

let
    Source = Json.Document(Web.Contents("https://api.propertydata.co.uk/prices?key=HEZEHOR0NC&postcode=SW161AG&bedrooms=4")),
    data = Source[data],
    #"Converted to Table" = Record.ToTable(data)
in
    #"Converted to Table"

【问题讨论】:

  • 以上不是 M 不是 VBA。如果使用 M 然后参数化字符串以在邮政编码中选择连接。您的 pc_ranges 将以列表对象的形式出现。在不知道 json 格式在邮政编码输出方面的规律性的情况下,vba 解决方案可能不适用于不同的用例。

标签: json excel vba web-scraping


【解决方案1】:

这假定 JSON 响应中有一组一致的对象类型,并使用 XMLHTTP 请求来获取 JSON 响应。这允许您使用在邮政编码中连接的 URL 查询字符串。用几个邮政编码测试。它使用JSON parser 来处理 JSON。导入JSONConverter.bas 后,您需要转到 VBE > 工具 > 引用并添加对 Microsoft Scripting Runtime 的引用。与您当前的 M 代码不同,这将列出 pc_ranges 值,而不仅仅是返回一个对象。

注意:您需要将 yourKeyGoesHere 替换为您的 API 密钥。

Option Explicit
Public r As Long
Public Sub GetInfoFromSheet()
    Application.ScreenUpdating = False
    Dim jsonStr As String, json As Object, item As Object, output As String
    Dim URL As String, postCode As String
    postCode = "SO419AA" '"SW161AG"
    URL = "https://api.propertydata.co.uk/prices?key=yourKeyGoesHere&postcode=" & postCode & "&bedrooms=4"
    r = 1

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", URL, False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        jsonStr = StrConv(.responseBody, vbUnicode)
    End With
    Set json = JsonConverter.ParseJson(jsonStr)
    emptyObject json
    Application.ScreenUpdating = True
End Sub
Public Sub emptyObject(ByVal json As Object)
    Dim key As Variant, item As Variant
    With ThisWorkbook.Worksheets("Sheet1")
        For Each key In json
            Select Case TypeName(json(key))
            Case "String", "Double"
                .Cells(r, 1) = key
                .Cells(r, 2) = json(key)
                r = r + 1
            Case "Dictionary"
                emptyObject json(key)
            Case "Collection"
                For Each item In json(key)
                    Select Case TypeName(item)
                    Case "Double"
                        .Cells(r, 1) = key
                        .Cells(r, 2) = item
                        r = r + 1
                    Case "Dictionary"
                        emptyObject item
                    End Select
                Next
            End Select
        Next
    End With
End Sub

【讨论】:

  • 你试过了吗?
猜你喜欢
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2015-03-11
相关资源
最近更新 更多