简体   繁体   English

VB6 / VBA 有 JSON 解析器吗?

[英]Is There a JSON Parser for VB6 / VBA?

I am trying to consume a web service in VB6. The service - which I control - currently can return a SOAP/XML message or JSON. I am having a really difficult time figuring out if VB6's SOAP type (version 1) can handle a returned object - as opposed to simple types like string , int , etc. So far I cannot figure out what I need to do to get VB6 to play with returned objects.我正在尝试在 VB6 中使用 web 服务。我控制的服务目前可以返回 SOAP/XML 消息或 JSON。我很难确定 VB6 的 SOAP 类型(版本 1)是否可以处理返回的object - 与stringint等简单类型相反。到目前为止,我无法弄清楚我需要做什么才能让 VB6 与返回的对象一起玩。

So I thought I might serialize the response in the web service as a JSON string.所以我想我可以将 web 服务中的响应序列化为 JSON 字符串。 Does a JSON parser exist for VB6? VB6 是否存在 JSON 解析器?

Check out JSON.org for an up-to-date list (see bottom of main page) of JSON parsers in many different languages. 请访问JSON.org ,以获取多种语言的JSON解析器的最新列表(请参阅主页底部)。 As of the time of this writing, you'll see a link to several different JSON parsers there, but only one is for VB6/VBA (the others are .NET): 在撰写本文时,您将在此处看到指向几个不同的JSON解析器的链接,但是只有一个用于VB6 / VBA(其他是.NET):

  • VB-JSON VB-JSON

    • When I tried to download the zip file, Windows said the data was corrupt. 当我尝试下载zip文件时,Windows表示数据已损坏。 However, I was able to use 7-zip to pull the files out. 但是,我能够使用7-zip提取文件。 It turns out that the main "folder" in the zip file isn't recognized as a folder by Windows, by 7-zip can see the contents of that main "folder," so you can open that up and then extract the files accordingly. 事实证明,Windows无法将zip文件中的主要“文件夹”识别为文件夹,通过7-zip可以看到该主要“文件夹”的内容,因此您可以将其打开,然后相应地提取文件。
    • The actual syntax for this VB JSON library is really simple: 这个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") 
    • Note: I had to add the "Microsoft Scripting Runtime" and "Microsoft ActiveX Data Objects 2.8" library as references via Tools > References in the VBA editor. 注意:我必须通过VBA编辑器中的“工具”>“引用”将“ Microsoft脚本运行时”和“ Microsoft ActiveX数据对象2.8”库添加为引用。
    • Note: VBJSON code is actually based on a google code project vba-json . 注意:VBJSON代码实际上是基于Google代码项目vba-json的 However, VBJSON promises several bug fixes from the original version. 但是,VBJSON承诺会从原始版本中修复一些错误。

Building on ozmike solution, which did not work for me (Excel 2013 and IE10). 建立在对我不起作用的ozmike解决方案上(Excel 2013和IE10)。 The reason is that I could not call the methods on the exposed JSON object. 原因是我无法在公开的JSON对象上调用方法。 So its methods are now exposed through functions attached to a DOMElement. 因此,它的方法现在通过附加到DOMElement的函数公开。 Didn't know this is possible (must be that IDispatch-thing), thank you ozmike. 不知道这是可能的(一定是IDispatch-thing),谢谢ozmike。

As ozmike stated, no 3rd-party libs, just 30 lines of code. 正如ozmike所说,没有第3方库,只有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

The following test constructs a JavaScript Object from scratch, then stringifies it. 以下测试从头开始构建一个JavaScript对象,然后对其进行字符串化。 Then it parses the object back and iterates over its keys. 然后,它将对象解析回并遍历其键。

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

outputs 输出

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

Hopefully this will be a big help to others who keep on coming to this page after searching for "vba json". 希望这对其他在搜索“ vba json”后继续进入此页面的人有很大帮助。

I found this page to be very helpful. 我发现此页面非常有帮助。 It provides several Excel-compatible VBA classes that deal with processing data in JSON format. 它提供了几个Excel兼容的VBA类,这些类处理JSON格式的数据。

VBA-JSON by Tim Hall, MIT licensed and on GitHub . 提姆·霍尔(Tim Hall)的VBA-JSON麻省理工学院许可),并在GitHub上 It's another fork of vba-json that emerged end of 2014. Claims to work on Mac Office and Windows 32bit and 64bit. 这是vba-json的另一个分支,出现在2014年底。声称可以在Mac Office和Windows 32位和64位上运行。

UPDATE: Found a safer way of parsing JSON than using Eval, this blog post shows the dangers of Eval ... http://exceldevelopmentplatform.blogspot.com/2018/01/vba-parse-json-safer-with-jsonparse-and.html 更新:找到了一种比使用Eval解析JSON更为安全的方法,此博客文章展示了Eval的危险... http://exceldevelopmentplatform.blogspot.com/2018/01/vba-parse-json-safer-with-jsonparse- and.html

Late to this party but sorry guys but by far the easiest way is to use Microsoft Script Control. 参加聚会晚了,但是对不起,但是到目前为止,最简单的方法是使用Microsoft Script Control。 Some sample code which uses VBA.CallByName to drill in 一些使用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

I have actually done a series of Q&As which explore JSON/VBA related topics. 我实际上已经进行了一系列问答,探讨了与JSON / VBA相关的主题。

Q1 In Excel VBA on Windows, how to mitigate issue of dot syntax traversal of parsed JSON broken by IDE's capitalisation behaviour? Q1 在Windows上的Excel VBA中,如何缓解IDE的大写行为破坏解析的JSON的点语法遍历的问题?

Q2 In Excel VBA on Windows, how to loop through a JSON array parsed? Q2 在Windows上的Excel VBA中,如何遍历解析的JSON数组?

Q3 In Excel VBA on Windows, how to get stringified JSON respresentation instead of “[object Object]” for parsed JSON variables? Q3 在Windows上的Excel VBA中,如何为解析的JSON变量获取字符串化的JSON表示形式而不是“ [object Object]”?

Q4 In Windows Excel VBA,how to get JSON keys to pre-empt “Run-time error '438': Object doesn't support this property or method”? Q4 在Windows Excel VBA中,如何获取JSON密钥以抢占“运行时错误'438':对象不支持此属性或方法”?

Q5 In Excel VBA on Windows, for parsed JSON variables what is this JScriptTypeInfo anyway? Q5 在Windows上的Excel VBA中,对于已解析的JSON变量,此JScriptTypeInfo到底是什么?

Here is a "Native" VB JSON library. 这是“本地” VB JSON库。

It is possible to use JSON that is already in IE8+. 可以使用IE8 +中已经存在的JSON。 This way your not dependent on a third party library that gets out of date and is untested. 这样,您就不必依赖过期且未经测试的第三方库。

see amedeus' alternative version here 在这里查看amedeus的替代版本

Sub myJSONtest()


Dim oJson As Object
Set oJson = oIE_JSON() ' See below gets IE.JSON object

' using json objects
Debug.Print oJson.parse("{ ""hello"": ""world"" }").hello ' world
Debug.Print oJson.stringify(oJson.parse("{ ""hello"": ""world"" }")) ' {"hello":"world"}

' getting items
Debug.Print oJson.parse("{ ""key1"": ""value1"" }").key1 ' value1
Debug.Print oJson.parse("{ ""key1"": ""value1"" }").itemGet("key1") ' value1
Debug.Print oJson.parse("[ 1234, 4567]").itemGet(1) '  4567

' change  properties
Dim o As Object
Set o = oJson.parse("{ ""key1"": ""value1"" }")
o.propSetStr "key1", "value\""2"
Debug.Print o.itemGet("key1") ' value\"2
Debug.Print oJson.stringify(o) ' {"key1":"value\\\"2"}
o.propSetNum "key1", 123
Debug.Print o.itemGet("key1") ' 123
Debug.Print oJson.stringify(o) ' {"key1":123}

' add properties
o.propSetNum "newkey", 123 ' addkey! JS MAGIC
Debug.Print o.itemGet("newkey") ' 123
Debug.Print oJson.stringify(o) ' {"key1":123,"newkey":123}

' assign JSON 'objects' to properties
Dim o2 As Object
Set o2 = oJson.parse("{ ""object2"": ""object2value"" }")
o.propSetJSON "newkey", oJson.stringify(o2) ' set object
Debug.Print oJson.stringify(o) ' {"key1":123,"newkey":{"object2":"object2value"}}
Debug.Print o.itemGet("newkey").itemGet("object2") ' object2value

' change array items
Set o = oJson.parse("[ 1234, 4567]") '
Debug.Print oJson.stringify(o) ' [1234,4567]
Debug.Print o.itemGet(1)
o.itemSetStr 1, "234"
Debug.Print o.itemGet(1)
Debug.Print oJson.stringify(o) ' [1234,"234"]
o.itemSetNum 1, 234
Debug.Print o.itemGet(1)
Debug.Print oJson.stringify(o) ' [1234,234]

' add array items
o.itemSetNum 5, 234 ' add items! JS Magic
Debug.Print o.itemGet(5) ' 234
Debug.Print oJson.stringify(o) ' [1234,234,null,null,null,234]

' assign JSON object to array item
o.itemSetJSON 3, oJson.stringify(o2)  ' assign object
Debug.Print o.itemGet(3) '[object Object]
Debug.Print oJson.stringify(o.itemGet(3)) ' {"object2":"object2value"}
Debug.Print oJson.stringify(o) ' [1234,234,null,{"object2":"object2value"},null,234]


oIE_JSON_Quit ' quit IE, must shut down or the IE sessions remain.
Debug.Print oJson.stringify(o) ' can use after but but IE server will shutdown... soon
End Sub

You can bridge to IE.JSON from VB. 您可以从VB桥接到IE.JSON。
Create a function oIE_JSON 创建一个函数oIE_JSON

Public g_IE As Object ' global


Public Function oIE_JSON() As Object


    ' for array access o.itemGet(0) o.itemGet("key1")
    JSON_COM_extentions = "" & _
            " Object.prototype.itemGet        =function( i ) { return this[i] }   ;            " & _
            " Object.prototype.propSetStr     =function( prop , val ) { eval('this.' + prop + '  = ""' + protectDoubleQuotes (val) + '""' )   }    ;            " & _
            " Object.prototype.propSetNum     =function( prop , val ) { eval('this.' + prop + '  = ' + val + '')   }    ;            " & _
            " Object.prototype.propSetJSON    =function( prop , val ) { eval('this.' + prop + '  = ' + val + '')   }    ;            " & _
            " Object.prototype.itemSetStr     =function( prop , val ) { eval('this[' + prop + '] = ""' + protectDoubleQuotes (val) + '""' )   }    ;            " & _
            " Object.prototype.itemSetNum     =function( prop , val ) { eval('this[' + prop + '] = ' + val )   }    ;            " & _
            " Object.prototype.itemSetJSON    =function( prop , val ) { eval('this[' + prop + '] = ' + val )   }    ;            " & _
            " function protectDoubleQuotes (str)   { return str.replace(/\\/g, '\\\\').replace(/""/g,'\\""');   }"

    ' document.parentwindow.eval dosen't work some versions of ie eg ie10?
     IEEvalworkaroundjs = "" & _
         " function IEEvalWorkAroundInit ()   { " & _
         " var x=document.getElementById(""myIEEvalWorkAround"");" & _
         " x.IEEval= function( s ) { return eval(s) } ; } ;"

    g_JS_framework = "" & _
      JSON_COM_extentions & _
      IEEvalworkaroundjs

    ' need IE8 and DOC type
    g_JS_HTML = "<!DOCTYPE html>  " & _
         " <script>" & g_JS_framework & _
                  "</script>" & _
         " <body>" & _
         "<script  id=""myIEEvalWorkAround""  onclick=""IEEvalWorkAroundInit()""  ></script> " & _
                 " HEllo</body>"

On Error GoTo error_handler

' Create InternetExplorer Object
Set g_IE = CreateObject("InternetExplorer.Application")
With g_IE
    .navigate "about:blank"
    Do While .Busy: DoEvents: Loop
    Do While .ReadyState <> 4: DoEvents: Loop
    .Visible = False ' control IE interface window
    .Document.Write g_JS_HTML
End With

Set objID = g_IE.Document.getElementById("myIEEvalWorkAround")
objID.Click ' create  eval
Dim oJson As Object

'Set oJson = g_IE.Document.parentWindow.Eval("JSON") ' dosen't work some versions of IE
Set oJson = objID.IEEval("JSON")

Set objID = Nothing
Set oIE_JSON = oJson

Exit Function
error_handler:
MsgBox ("Unexpected Error, I'm quitting. " & Err.Description & ".  " & Err.Number)
g_IE.Quit
Set g_IE = Nothing

End Function

Public Function oIE_JSON_Quit()
         g_IE.Quit
         Exit Function
End Function

Up vote if you find useful 如果您觉得有用,请进行投票

VB6-JsonBag,另一个JSON解析器/生成器也应该可以轻松导入到VBA中。

You could write an Excel-DNA Add-in in VB.NET. 您可以在VB.NET中编写一个Excel-DNA加载项。 Excel-DNA is a thin library that lets you write XLLs in .NET. Excel-DNA是一个瘦库,可让您在.NET中编写XLL。 This way you get access to the entire .NET universe and can use stuff like http://james.newtonking.com/json - a JSON framework that deserializes JSON in any custom class. 这样,您就可以访问整个.NET Universe,并且可以使用诸如http://james.newtonking.com/json之类的东西-一种在任何自定义类中反序列化JSON的JSON框架。

If you are interested, here's a write up of how to build a generic Excel JSON client for Excel using VB.NET: 如果您有兴趣,这里是有关如何使用VB.NET为Excel构建通用Excel JSON客户端的文章:

http://optionexplicitvba.com/2014/05/09/developing-a-json-excel-add-in-with-vb-net/ http://optionexplicitvba.com/2014/05/09/developing-a-json-excel-add-in-with-vb-net/

And here's the link to the code: https://github.com/spreadgit/excel-json-client/blob/master/excel-json-client.dna 这是代码的链接: https : //github.com/spreadgit/excel-json-client/blob/master/excel-json-client.dna

I would suggest using a .Net component. 我建议使用.Net组件。 You can use .Net components from VB6 via Interop - here's a tutorial . 您可以通过Interop使用VB6中的.Net组件-这是一个教程 My guess is that .Net components will be more reliable and better supported than anything produced for VB6. 我的猜测是,.Net组件将比为VB6生产的任何组件更加可靠并且得到更好的支持。

There are components in the Microsoft .Net framework like DataContractJsonSerializer or JavaScriptSerializer . Microsoft .Net框架中有一些组件,例如DataContractJsonSerializerJavaScriptSerializer You could also use third party libraries like JSON.NET . 您还可以使用第三方库,例如JSON.NET

As Json is nothing but strings so it can easily be handled if we can manipulate it the right way, no matter how complex the structure is. 由于Json只是字符串而已,因此,只要我们能够以正确的方式对其进行操作,无论结构多么复杂,都可以轻松地对其进行处理。 I don't think it is necessary to use any external library or converter to do the trick. 我认为没有必要使用任何外部库或转换器来完成此操作。 Here is an example where I've parsed json data using string manipulation. 这是一个使用字符串操作解析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

Understand this is an old post, but I recently stumbled upon it while adding web service consumption to an old VB6 app. 理解这是一个古老的帖子,但是我最近在将Web服务消耗添加到一个旧的VB6应用程序时偶然发现了它。 The accepted answer (VB-JSON) is still valid and appears to work. 接受的答案(VB-JSON)仍然有效,并且似乎可以使用。 However, I discovered that Chilkat has been updated to include REST and JSON functionality, making it a one-stop (though paid) tool for me. 但是,我发现Chilkat已更新为包括REST和JSON功能,从而使其成为我的一站式(尽管付费)工具。 They even have an online code generator that generates the code to parse pasted JSON data. 他们甚至还有一个在线代码生成器,用于生成代码以分析粘贴的JSON数据。

JsonObject link JsonObject链接

Code Generator link 代码生成器链接

Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. 在ScriptControl之上,使用解析JSON的JavaScript功能,我们可以在VBA中创建解析器,该解析器将列出JSON中的每个数据点。 No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure. 无论数据结构如何嵌套或复杂,只要我们提供有效的JSON,此解析器都将返回完整的树结构。

JavaScript's Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON. JavaScript的Eval,getKeys和getProperty方法提供了用于验证和读取JSON的构造块。

Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. 结合VBA中的递归函数,我们可以遍历JSON字符串中的所有键(直到第n级)。 Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required. 然后使用Tree控件(在本文中使用)或字典,甚至在简单的工作表上,我们都可以根据需要排列JSON数据。

Full VBA Code here.Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. 这里是完整的VBA代码。在ScriptControl之上,使用解析JSON的JavaScript功能,我们可以在VBA中创建一个解析器,该解析器将列出JSON中的每个数据点。 No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure. 无论数据结构如何嵌套或复杂,只要我们提供有效的JSON,此解析器都将返回完整的树结构。

JavaScript's Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON. JavaScript的Eval,getKeys和getProperty方法提供了用于验证和读取JSON的构造块。

Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. 结合VBA中的递归函数,我们可以遍历JSON字符串中的所有键(直到第n级)。 Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required. 然后使用Tree控件(在本文中使用)或字典,甚至在简单的工作表上,我们都可以根据需要排列JSON数据。

Full VBA Code here. 完整的VBA代码在这里。

Formula in an EXCEL CELL EXCEL CELL中的公式

=JSON2("{mykey:1111, mykey2:{keyinternal1:22.1,keyinternal2:22.2}, mykey3:3333}", "mykey2", "keyinternal2")

DISPLAYS: 22.2 显示器:22.2

=JSON("{mykey:1111,mykey2:2222,mykey3:3333}", "mykey2")

DISPLAYS: 2222 显示器:2222

  • INSTRUCTIONS: 说明:
  • Step1. 第1步。 press ALT+F11 按ALT + F11
  • Step2. 第2步。 Insert -> Module 插入->模块
  • Step3. 第三步 tools -> references -> tick Microsoft Script Control 1.0 工具->参考->勾选Microsoft Script Control 1.0
  • Step4. 第四步。 paste this below. 将此粘贴在下面。
  • Step5. 第五步 ALT+Q close VBA window. ALT + Q关闭VBA窗口。

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

Public Function JSON(sJsonString As String, Key As String) As String
On Error GoTo err_handler

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

    Dim objJSON As Object
    Set objJSON = oScriptEngine.Eval("(" + sJsonString + ")")

    JSON = VBA.CallByName(objJSON, Key, VbGet)

Err_Exit:
    Exit Function

err_handler:
    JSON = "Error: " & Err.Description
    Resume Err_Exit

End Function


Public Function JSON2(sJsonString As String, Key1 As String, Key2 As String) As String
On Error GoTo err_handler

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

    Dim objJSON As Object
    Set objJSON = oScriptEngine.Eval("(" + sJsonString + ")")

    JSON2 = VBA.CallByName(VBA.CallByName(objJSON, Key1, VbGet), Key2, VbGet)

Err_Exit:
    Exit Function

err_handler:
    JSON2 = "Error: " & Err.Description
    Resume Err_Exit

End Function

this is vb6 example code, tested ok,works done 这是vb6的示例代码,测试正常,工作完成

from the above good examples, i made changes and got this good result 从上面的好例子中,我进行了更改并获得了很好的结果

it can read keys {} and arrays [] 它可以读取键{}和数组[]

Option Explicit
'in vb6 click "Tools"->"References" then
'check the box "Microsoft Script Control 1.0";
Dim oScriptEngine As New ScriptControl
Dim objJSON As Object

''to use it
Private Sub Command1_Click()
  MsgBox JsonGet("key1", "{'key1': 'value1'  ,'key2': { 'key3': 'value3' } }")''returns "value1"
  MsgBox JsonGet("key2.key3", "{'key1': 'value1'  ,'key2': { 'key3': 'value3' } }") ''returns "value3"
  MsgBox JsonGet("result.0.Ask", "{'result':[{'MarketName':'BTC-1ST','Bid':0.00004718,'Ask':0.00004799},{'MarketName':'BTC-2GIVE','Bid':0.00000073,'Ask':0.00000074}]}") ''returns "0.00004799"
  MsgBox JsonGet("mykey2.keyinternal1", "{mykey:1111, mykey2:{keyinternal1:22.1,keyinternal2:22.2}, mykey3:3333}") ''returns "22.1"
End Sub

Public Function JsonGet(eKey$, eJsonString$, Optional eDlim$ = ".") As String
  Dim tmp$()
  Static sJsonString$
  If Trim(eKey$) = "" Or Trim(eJsonString$) = "" Then Exit Function
  If sJsonString <> eJsonString Then
    sJsonString = eJsonString
    oScriptEngine.Language = "JScript"
    Set objJSON = oScriptEngine.Eval("(" + eJsonString + ")")
  End If
  tmp = Split(eKey, eDlim)
  If UBound(tmp) = 0 Then JsonGet = VBA.CallByName(objJSON, eKey, VbGet): Exit Function

  Dim i&, o As Object
  Set o = objJSON
  For i = 0 To UBound(tmp) - 1
    Set o = VBA.CallByName(o, tmp(i), VbGet)
  Next i
  JsonGet = VBA.CallByName(o, tmp(i), VbGet)
  Set o = Nothing
End Function

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
  Set objJSON = Nothing
End Sub

Whether you need it for VB6, VBA, VB.NET, C#, Delphi or pretty much any other programming language on the Windows platform, check JSON Essentials<\/a> .无论您需要它用于 VB6、VBA、VB.NET、C#、Delphi 还是 Windows 平台上的几乎任何其他编程语言,请查看JSON Essentials<\/a> 。 Its capabilities go well beyond just parsing and querying JSON.它的功能远不止解析和查询 JSON。 Using JSON Essentials you can serialize objects into JSON, make JSON HTTP calls and get parsed JSON DOM in response if you need it, re-formatting JSON, using files, registry, memory streams, or HTTP\/HTTPS for writing and loading JSON data in UTF-8\/16\/32 and ASCII\/EASCII encodings, and it comes with JSON Schema support.使用 JSON Essentials,您可以将对象序列化为 JSON,进行 JSON HTTP 调用并在需要时获取解析的 JSON DOM 作为响应,重新格式化 JSON,使用文件、注册表、内存流或 HTTP\/HTTPS 来写入和加载 JSON 数据UTF-8\/16\/32 和 ASCII\/EASCII 编码,它带有 JSON Schema 支持。 On top of that it's exceptionally fast, stable, standard compliant, being actively developed and supported.最重要的是,它非常快速、稳定、符合标准,正在积极开发和支持。 And it has a free<\/strong> license too.它也有一个免费<\/strong>的许可证。

Here are some quick samples, the first one shows how to parse and query JSON:以下是一些快速示例,第一个示例显示了如何解析和查询 JSON:

' Create JSON document object.
Dim document As JsonDocument
Set document = New JsonDocument

' Parse JSON.
document.parse "{""a"":true,""b"":123,""c"":{},""d"":[""abc""]}"

' Select the first node of the 'd' node using JSON Pointer
' starting from the root document node.
Dim node_abc As IJsonNode
Set node_abc = document.root.select("/d/0")

' Select node 'a' starting from the previously selected
' first child node of node 'd' and traversing first up to
' the root node and then down to node 'a' using Relative
' JSON Pointer.
Dim node_a As IJsonNode
Set node_a = node_abc.select("rel:2/a")

Here is a new one: [VB6/VBA] JSON parsing to built-in VBA.Collections with JSON Path support这是一个新的: [VB6/VBA] JSON 解析为内置 VBA.Collections 和 JSON 路径支持

It's a single self-contained module (no classes), parses JSON to nested built-in Collections (fast and lean) and supports practical subset of JSON Path (aka XPath for JSON) to retrieve values.它是一个独立的模块(无类),将 JSON 解析为嵌套的内置 Collections(快速且精简)并支持 JSON 路径的实用子集(对于 JSON 也称为 XPath)以检索值。

This means that there is no need to madly nest Item calls like这意味着不需要像这样疯狂地嵌套Item调用

oJson.Item("first").Item("second").Item("array").Item(0)`

. . . . . . but to access nested values can just use a single call to但要访问嵌套值,只需调用一次即可

JsonValue(oJson, "$.first.second.array[0]")

. . . . . . and retrieve data from as deep in the hierarchy as needed.并根据需要从层次结构的最深处检索数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM