【问题标题】:Parsing a JSON Object in VBA [duplicate]在 VBA 中解析 JSON 对象 [重复]
【发布时间】:2023-03-07 07:49:01
【问题描述】:

我在 VBA 中解析一个 JSON 对象。我在这个论坛上找到了一个很好的代码示例。但是,对象中的字段之一是“总计”。在我的代码中,我试图获得总数,但“总数”正在切换为“总数”。我在运行时收到错误 438。这是代码片段:

Dim Issues As Object
Dim scriptControl As Object

Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"

Set ObjHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")

URL = "http://<url>.com:10005/rest/api/2/search"

ObjHTTP.Open "POST", URL, False
ObjHTTP.SetRequestHeader "Authorization", "Basic <userid / password>"
ObjHTTP.SetRequestHeader "Content-Type", "application/json"

'Get the new work intake for the month.
ObjHTTP.send ("{""jql"":""<my query here>"":[""id""],""maxResults"":1}")
strX = ObjHTTP.responsetext
Set Issues = scriptControl.Eval("(" + strX + ")")

With Sheets("Test")
    .Cells(1, 1) = Issues.expand  --this works
    .Cells(1, 2) = Issues.startAt --this works
    .Cells(1, 3) = Issues.maxResults -- this works
    .Cells(1, 4) = Issues.Total  -- JSON object is "total"  editor keeps switching to "Total"
End With

有谁知道为什么我不能使用 Issues.total?

【问题讨论】:

  • VBA 是不区分大小写的语言,JScript 对象Issues 区分大小写。要么使用CallByName(Issues, "total", vbGet),要么使用JSON parserIssues("total")

标签: json vba jscript


【解决方案1】:

借用链接的问题,这样的事情应该可以工作:

'.... 
strX = ObjHTTP.responsetext
scriptControl.Eval("var o = (" + strX + ");")
scriptControl.AddCode "function getProp(propName) { return o[propName]; } "

With Sheets("Test")
    .Cells(1, 1) = scriptControl.Run("getProp", "expand")  
    .Cells(1, 2) = scriptControl.Run("getProp", "startAt")
    .Cells(1, 3) = scriptControl.Run("getProp", "maxResults")
    .Cells(1, 4) = scriptControl.Run("getProp", "total")
End With

话虽如此,您应该改用以下代码:https://github.com/VBA-tools/VBA-JSON

【讨论】:

  • 感谢您的回复。这行得通!正是我需要的。
  • @omegastripes - 感谢修复
猜你喜欢
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多