【问题标题】:Firebase REST API not parsing JSON when using VBA in Excel在 Excel 中使用 VBA 时 Firebase REST API 不解析 JSON
【发布时间】:2018-08-13 13:24:27
【问题描述】:

我在使用其余 API 将 JSON 数据发送到 firebase 数据库时遇到问题,数据已发送,但无法解析。例如,如果我在 Windows 的命令提示符中使用此 curl 命令:

curl -X PUT -d  "{\"lastName\":\"Jones\",\"firstName\":\"Bubba\"}"   https://<database-name>.firebaseio.com/rest/test/.json

这会导致正确解析数据:

然而,当使用以下 VBA 代码时:

Sub PUSHhttpRequestTest()  'Doesn't Work!!

    Dim sc As Object
    Set sc = CreateObject("ScriptControl")
    sc.Language = "JScript"

    Dim strURL As String: strURL = "https://<database-name>.firebaseio.com/rest/.json"

    Dim strRequest
    strRequest = """{\""lastName\"":\""Jones\"",\""firstName\"":\""Bubba\""}"""
    Dim XMLhttp: Set XMLhttp = CreateObject("msxml2.xmlhttp")
    Dim response As String
    Debug.Print strRequest
    XMLhttp.Open "PUT", strURL, False
    XMLhttp.setrequestheader "Content-Type", "application/json;charset=UTF-8"
    XMLhttp.sEnd strRequest
    response = XMLhttp.responseText
    Debug.Print response
End Sub

这会发送完全相同的字符串化 JSON,并将其添加到 Firebase 数据库,但是 JSON 字符串不会被解析:

我尝试了不同的内容类型和 JSON 字符串的变体,但似乎没有任何效果。谁能解释我如何让 VBA 脚本发送 Firebase 将解析的数据?

谢谢

【问题讨论】:

    标签: json excel firebase firebase-realtime-database


    【解决方案1】:

    我找到了一种将 JSON 数据从 excel 发送到 firebase 的可能解决方案,但它没有回答我的问题,即为什么上面发送字符串化 JSON 的 VBA 代码没有在 Firebase 中得到解析。我仍然想要一个解决方案,因为我已经有一个从我的数据创建字符串化 JSON 的函数。

    使用来自this Stack Overflow postVBA-web Library 似乎可以解决问题。该示例使用字典存储您的数据,但请my comment and the subsequent reply 了解要发送的 JSON 字符串的格式。 不需要转义码!

    json 没有 PUT 和其他请求类型,但您可以轻松地将这些添加到自己中。

    上面的等效代码,但使用 VBA-web 库(带有自定义 PutJson 函数)是:

    Sub test()
    
    Dim strURL As String: strURL = "https://<database-name>/rest/test/whatwhat/.json"
    Dim strRequest As String: strRequest = "{""LastName"":""Jones"",""firstName"":""Bubba""}"
    
    Dim Client As New WebClient
    Dim Response As WebResponse
    Set Response = Client.PutJson(strURL, strRequest)
    
    ActiveSheet.Range("A1").Value = Response.Content
    End Sub
    

    我们最终得到了这个......

    快乐的日子!

    不过,我还是想知道为什么看似相同的 curl 和 VBA HTTP 请求会导致 FireBase 中的数据解析不同?

    【讨论】:

      猜你喜欢
      • 2011-10-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多