是否有适用于VB6/VBA的JSON解析器?

Ben*_*ack 39 vb6 serialization vba json web-services

我试图在VB6中使用Web服务.我控制的服务 - 当前可以返回SOAP/XML消息或JSON.我有一个非常困难的时候,如果VB6的SOAP类型(第1版)找出可以处理返回object-而不是简单的类型,如string,int等.到目前为止,我想不出什么,我需要做的就是VB6而归玩对象.

所以我想我可能会将Web服务中的响应序列化为JSON字符串.VB6是否存在JSON解析器?

Ben*_*ack 41

查看JSON.org以获取许多不同语言的JSON解析器的最新列表(请参阅主页的底部).截至撰写本文时,您将看到两个不同JSON解析器的链接:

  • VB-JSON

    • 当我试图下载zip文件时,Windows表示数据已损坏.但是,我能够使用7-zip拉出文件.事实证明,zip文件中的主"文件夹"不被Windows识别为文件夹,7-zip可以看到该主文件夹的内容,因此您可以打开它然后相应地提取文件.
    • 这个VB JSON库的实际语法非常简单:

      Dim p As Object
      Set p = JSON.parse(strFormattedJSON)
      
      'Print the text of a nested property '
      Debug.Print p.Item("AddressClassification").Item("Description")
      
      'Print the text of a property within an array '
      Debug.Print p.Item("Candidates")(4).Item("ZipCode")
      
      Run Code Online (Sandbox Code Playgroud)
    • 注意:我必须通过VBA编辑器中的工具>引用添加"Microsoft Scripting Runtime"和"Microsoft ActiveX Data Objects 2.8"库作为参考.
    • 注意:VBJSON代码实际上是基于谷歌代码项目vba-json.但是,VBJSON承诺从原始版本修复几个错误.
  • PW.JSON
    • 这实际上是一个VB.NET库,所以我没有花太多时间研究它.


Wol*_*ehn 14

以ozmike解决方案为基础,这对我不起作用(Excel 2013和IE10).原因是我无法在公开的JSON对象上调用方法.因此,它的方法现在通过附加到DOMElement的函数公开.不知道这是可能的(必须是IDispatch-thing),谢谢你.

正如ozmike所说,没有第三方库,只有30行代码.

Option Explicit

Public JSON As Object
Private ie As Object

Public Sub initJson()
    Dim html As String

    html = "<!DOCTYPE html><head><script>" & _
    "Object.prototype.getItem=function( key ) { return this[key] }; " & _
    "Object.prototype.setItem=function( key, value ) { this[key]=value }; " & _
    "Object.prototype.getKeys=function( dummy ) { keys=[]; for (var key in this) if (typeof(this[key]) !== 'function') keys.push(key); return keys; }; " & _
    "window.onload = function() { " & _
    "document.body.parse = function(json) { return JSON.parse(json); }; " & _
    "document.body.stringify = function(obj, space) { return JSON.stringify(obj, null, space); }" & _
    "}" & _
    "</script></head><html><body id='JSONElem'></body></html>"

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .navigate "about:blank"
        Do While .Busy: DoEvents: Loop
        Do While .readyState <> 4: DoEvents: Loop
        .Visible = False
        .document.Write html
        .document.Close
    End With

    ' This is the body element, we call it JSON:)
    Set JSON = ie.document.getElementById("JSONElem")

End Sub

Public Function closeJSON()
    ie.Quit
End Function
Run Code Online (Sandbox Code Playgroud)

以下测试从头开始构造JavaScript对象,然后对其进行字符串化.然后它将对象解析回来并迭代其键.

Sub testJson()
    Call initJson

    Dim jsObj As Object
    Dim jsArray As Object

    Debug.Print "Construction JS object ..."
    Set jsObj = JSON.Parse("{}")
    Call jsObj.setItem("a", 1)
    Set jsArray = JSON.Parse("[]")
    Call jsArray.setItem(0, 13)
    Call jsArray.setItem(1, Math.Sqr(2))
    Call jsArray.setItem(2, 15)
    Call jsObj.setItem("b", jsArray)

    Debug.Print "Object: " & JSON.stringify(jsObj, 4)

    Debug.Print "Parsing JS object ..."
    Set jsObj = JSON.Parse("{""a"":1,""b"":[13,1.4142135623730951,15]}")

    Debug.Print "a: " & jsObj.getItem("a")
    Set jsArray = jsObj.getItem("b")
    Debug.Print "Length of b: " & jsArray.getItem("length")
    Debug.Print "Second element of b: "; jsArray.getItem(1)

    Debug.Print "Iterate over all keys ..."
    Dim keys As Object
    Set keys = jsObj.getKeys("all")

    Dim i As Integer
    For i = 0 To keys.getItem("length") - 1
        Debug.Print keys.getItem(i) & ": " & jsObj.getItem(keys.getItem(i))
    Next i

    Call closeJSON
End Sub
Run Code Online (Sandbox Code Playgroud)

输出

Construction JS object ...
Object: {
    "a": 1,
    "b": [
        13,
        1.4142135623730951,
        15
    ]
}
Parsing JS object ...
a: 1
Length of b: 3
Second element of b:  1,4142135623731 
Iterate over all keys ...
a: 1
b: 13,1.4142135623730951,15
Run Code Online (Sandbox Code Playgroud)


das*_*mug 7

我知道这是一个古老的问题,但我的回答对希望在搜索"vba json"之后继续访问此页面的其他人有很大的帮助.

我发现这个页面非常有用.它提供了几个与Excel兼容的VBA类,用于处理JSON格式的数据处理.


SIM*_*SIM 7

由于 Json 只是字符串,因此如果我们能够以正确的方式操作它,无论结构多么复杂,它都可以轻松处理。我认为没有必要使用任何外部库或转换器来实现这一目的。这是我使用字符串操作解析 json 数据的示例。

Sub GetJsonContent()
    Dim http As New XMLHTTP60, itm As Variant

    With http
        .Open "GET", "http://jsonplaceholder.typicode.com/users", False
        .send
        itm = Split(.responseText, "id"":")
    End With

    x = UBound(itm)

    For y = 1 To x
        Cells(y, 1) = Split(Split(itm(y), "name"": """)(1), """")(0)
        Cells(y, 2) = Split(Split(itm(y), "username"": """)(1), """")(0)
        Cells(y, 3) = Split(Split(itm(y), "email"": """)(1), """")(0)
        Cells(y, 4) = Split(Split(itm(y), "street"": """)(1), """")(0)
    Next y
End Sub
Run Code Online (Sandbox Code Playgroud)


Pat*_*ker 5

提姆·霍尔(Tim Hall)的 VBA-JSON麻省理工学院许可),并在 GitHub上。这是 vba-json的另一个分支,出现在2014年底。声称可以在32位和64位Mac Office和Windows上运行。


S M*_*den 5

更新:找到一种比使用Eval更安全的解析JSON的方法,这篇博文显示了Eval的危险... http://exceldevelopmentplatform.blogspot.com/2018/01/vba-parse-json-safer-with-jsonparse- and.html

迟到这个派对但对不起家伙,但到目前为止最简单的方法是使用Microsoft Script Control.一些使用VBA.CallByName钻取的示例代码

'Tools->References->
'Microsoft Script Control 1.0;  {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:\Windows\SysWOW64\msscript.ocx

Private Sub TestJSONParsingWithCallByName()

    Dim oScriptEngine As ScriptControl
    Set oScriptEngine = New ScriptControl
    oScriptEngine.Language = "JScript"

    Dim sJsonString As String
    sJsonString = "{'key1': 'value1'  ,'key2': { 'key3': 'value3' } }"


    Dim objJSON As Object
    Set objJSON = oScriptEngine.Eval("(" + sJsonString + ")")
    Debug.Assert VBA.CallByName(objJSON, "key1", VbGet) = "value1"
    Debug.Assert VBA.CallByName(VBA.CallByName(objJSON, "key2", VbGet), "key3", VbGet) = "value3"

End Sub
Run Code Online (Sandbox Code Playgroud)

我实际上已经完成了一系列问答,探讨了与JSON/VBA相关的主题.

Q1 在Windows上的Excel VBA中,如何减轻由IDE的大小写行为破坏的解析JSON的点语法遍历问题?

Q2 在Windows上的Excel VBA中,如何循环解析JSON数组?

Q3 在Windows上的Excel VBA中,如何为已解析的JSON变量获取字符串化的JSON表示而不是"[object Object]"?

Q4 在Windows Excel VBA中,如何获取JSON键以抢占"运行时错误'438':对象不支持此属性或方法"?

Q5 在Windows上的Excel VBA中,对于已解析的JSON变量,这个JScriptTypeInfo究竟是什么?

  • 这似乎不适用于 64 位,因为 Microsoft 没有将其移植到 64 位! (2认同)