【问题标题】:parse JSON array in excel vba在excel vba中解析JSON数组
【发布时间】:2018-03-18 02:30:09
【问题描述】:

我已经完成了一个帖子 URL,我得到了 JSON 格式的响应文本。 我想从 cell(1,1) 开始获取“条形码” 这就是 JSON 响应:

"{
    ""status"": ""success"",
    ""message"": ""5 New Barcode(s) Generated for batch 5924592"",
    ""data"": {
        ""batch"": ""5924592"",
        ""barcodes"": [
            ""MN8HY6"",
            ""5BZZ9K"",
            ""9R6QKR"",
            ""869P8Z"",
            ""XK2UXZ""
        ]
    }
}"

这是我迄今为止在 VBA excel 上写的内容

Dim Json As Object
Dim xmlhttp As New MSXML2.XMLHTTP60
Dim Parsed As Dictionary 
Dim Item As Dictionary    

'Post
xmlhttp.Open "POST", "url", False
'setting auth headers
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.setRequestHeader "Authorization", "token"

Dim Bqty As Variant
Dim bID As Variant

Bqty = Sheets("sheet1").Range("f1").Value
bID = Sheets("sheet1").Range("f4").Value

xmlhttp.send "action=" & "createBarcodes" & _
Chr(38) & "barcodes=" & Bqty & _
Chr(38) & "batch=" & bID


JsonString = xmlhttp.responseText

Set Json = JsonConverter.ParseJson(xmlhttp.responseText)
Set Parsed = JsonConverter.ParseJson(xmlhttp.responseText)

 Dim i As Integer
 i = 1
 For Each Item In Parsed("data")
 Sheets("Batch ID").Cells(i, 1).Value = Item("barcodes")
 i = i + 1
 Next

请如果有人可以提供帮助,因为我已经花了一整天的时间来解决这个问题。我不是专业的 VBA 开发人员。

谢谢

【问题讨论】:

  • 我在运行脚本时收到错误消息“需要对象”:(

标签: arrays json excel http-post vba


【解决方案1】:

您需要 JSON 库吗?

Dim i As Long, strresp As String, bcodes As Variant

strresp = xmlhttp.responseText

strresp = Mid(strresp, InStr(1, strresp, Chr(91) & Chr(32) & Chr(34) & Chr(34)) + 4)
strresp = Left(strresp, InStrRev(strresp, Chr(34) & Chr(34) & Chr(32) & Chr(93)) - 1)

bcodes = Split(strresp, Chr(34) & Chr(34) & Chr(44) & Chr(32) & Chr(34) & Chr(34))

For i = LBound(bcodes) To UBound(bcodes)
    Debug.Print bcodes(i)
Next i

Worksheets("Batch ID").Cells(1, 1).Resize(UBound(bcodes) + 1, 1) = _
    Application.Transpose(bcodes)

授予所有 Chr() 让它看起来很乱,但我讨厌在带引号的字符串中加倍引号。

【讨论】:

  • 我同意双引号。我更喜欢在这种情况下使用 const:Const dq = Chr(34) & Chr(34)。可能不是最好的编程策略,但有时我并不以最佳实践而闻名
  • 这只是一个演示,它的实用性将取决于 responseText 实际 的样子。最好将 [] 之间的字符串中间,然后从那里正则表达式输出条形码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
相关资源
最近更新 更多