Y a-t-il un analyseur JSON pour VB6 / VBA?

j'essaie de consommer un service web en VB6. Le service - que je contrôle - peut actuellement renvoyer un message SOAP / XML ou JSON. J'ai vraiment du mal à comprendre si le type SOAP de VB6 (version 1) peut supporter un retour object - par opposition à des types simples comme string , int , etc. Jusqu'à présent, je n'arrive pas à trouver ce que je dois faire pour que VB6 joue avec les objets retournés.

donc j'ai pensé que je pourrais sérialiser la réponse dans le web servir en tant que chaîne JSON. Existe-t-il un analyseur JSON pour VB6?

37
demandé sur Jocelyn 2010-05-06 19:03:13

13 réponses

Check out JSON.org pour une liste à jour (voir en bas de la page principale) des analyseurs JSON en plusieurs langues. Au moment de la rédaction du présent article, vous y verrez un lien vers deux parsers JSON différents:

  • VB-JSON

    • lorsque J'ai essayé de télécharger le fichier zip, Windows a dit que les données étaient corrompues. Cependant, j'ai pu utiliser 7-zip pour extraire les fichiers. Il s'avère que le "dossier" dans le fichier zip n'est pas reconnu en tant que dossier par Windows, 7-zip pouvez voir le contenu de ce "dossier", de sorte que vous pouvez ouvrir jusqu'puis extraire les fichiers en conséquence.
    • la syntaxe actuelle de cette bibliothèque VB JSON est vraiment simple:

      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: j'ai dû ajouter les" Microsoft Scripting Runtime "et" Microsoft ActiveX Data Objects 2.8" bibliothèque comme références via les outils > références dans L'éditeur VBA.
    • Note: le code VBJSON est en fait basé sur un projet de code google vba-json . Cependant, VBJSON promet plusieurs corrections de bogues de la version originale.
  • PW.JSON
    • c'est en fait une bibliothèque pour VB.NET , donc je n'ai pas passé beaucoup de temps à regarder.
38
répondu Ben McCormack 2013-07-19 12:48:26

S'appuyant sur la solution ozmike, qui n'a pas fonctionné pour moi (Excel 2013 et IE10). La raison est que je ne pouvais pas appeler les méthodes sur l'objet JSON exposé. Ainsi ses méthodes sont maintenant exposées par des fonctions attachées à un dôme. Je ne savais pas que c'était possible (ça doit être ce truc D'IDispatch), merci ozmike.

comme ozmike l'a déclaré, pas de libs tiers, juste 30 lignes de code.

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

le test suivant construit un JavaScript Objet à partir de zéro, puis stringifie. Puis il analyse l'objet et itère sur ses touches.

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

sorties

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
13
répondu Wolfgang Kuehn 2014-02-09 20:58:12

je sais que c'est une vieille question, mais j'espère que ma réponse sera d'une grande aide pour les autres qui continuent à venir à cette page après avoir cherché"vba json".

j'ai trouvé ce page très utile. Il fournit plusieurs classes VBA compatibles Excel qui traitent le traitement des données dans le format JSON.

7
répondu dashmug 2012-06-14 17:19:53

Voici une bibliothèque VB JSON "Native".

il est possible d'utiliser JSON qui est déjà dans IE8+. De cette façon, Votre ne dépend pas d'une bibliothèque tierce partie qui se démodent et n'est pas testé.

voir la version alternative d'amedeus ici

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

vous pouvez passer à IE.JSON à partir de VB.

Créer une fonction 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

Jusqu'vote si vous trouvez utile

4
répondu ozmike 2017-05-23 12:10:26

VBA-JSON par Tim Hall, , sous licence MIT, et sur GitHub . C'est une autre bifurcation de vba-json qui a émergé fin 2014. Prétend travailler sur Mac Office et Windows 32bit et 64bit.

4
répondu Patrick Böker 2015-07-09 14:22:16

mise à JOUR: Trouvé un moyen plus sûr de parsing JSON que l'utilisation d'Eval, ce blog montre les dangers de Eval ... http://exceldevelopmentplatform.blogspot.com/2018/01/vba-parse-json-safer-with-jsonparse-and.html

en retard à cette fête mais désolé les gars, mais de loin la manière la plus facile est D'utiliser Microsoft Script Control. Un exemple de code qui utilise VBA.CallByName de percer dans

'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

j'ai en fait fait fait une série de questions et réponses qui explorent JSON/VBA sujets connexes.

Q1 in Excel VBA on Windows, how to mitige issue of dot syntax traversal of parsed JSON broken by IDE capitalization behaviour?

Q2 en Excel VBA sur Windows, Comment faire une boucle à travers un tableau JSON parsed?

Q3 dans Excel VBA sur Windows, Comment obtenir stringified JSON resprésentation à la place de "[Objet Objet] " pour les variables JSON analysées?

Q4 dans Windows Excel VBA, comment obtenir les clés JSON pour préempter "erreur D'exécution '438': objet ne supporte pas cette propriété ou méthode"?

Q5 Dans Excel VBA sur Windows, pour analysée JSON variables qu'est-ce que ce JScriptTypeInfo de toute façon?

4
répondu S Meaden 2018-01-27 18:45:35

VB6 - JsonBag, un autre analyseur/générateur JSON devrait aussi pouvoir être importé dans VBA avec peu de problèmes.

3
répondu Bob77 2013-10-21 07:30:03

je suggère d'utiliser un composant .Net. Vous pouvez utiliser les composants .Net à partir de VB6 via Interop - voici un tutorial . Je pense que les composants .Net seront plus fiables et mieux supportés que tout ce qui est produit pour VB6.

il y a des composants dans le cadre Microsoft .Net comme DataContractJsonSerializer ou JavaScriptSerializer . Vous pouvez aussi utiliser des tiers bibliothèques du parti comme JSON.NET .

2
répondu MarkJ 2010-05-07 08:46:17

vous pourriez écrire un Excel-ADN Add-in dans VB.NET. Excel-DNA est une bibliothèque fine qui vous permet d'écrire des XLLs .NET. De cette façon, vous accédez à L'ensemble de L'univers .NET et pouvez utiliser des choses comme http://james.newtonking.com/json - un cadre JSON qui désérialise JSON dans n'importe quelle classe personnalisée.

si vous êtes intéressé, voici une écriture de comment construire un client Excel JSON générique pour Excel en utilisant VB.NET:

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

et voici le lien vers le code: https://github.com/spreadgit/excel-json-client/blob/master/excel-json-client.dna

2
répondu Bjoern Stiel 2014-05-11 09:02:56

en utilisant les fonctionnalités JavaScript de parsing JSON, en plus de ScriptControl, nous pouvons créer un analyseur dans VBA qui listera chaque point de données à l'intérieur du JSON. Peu importe comment imbriqué ou complexe la structure de données est, aussi longtemps que nous fournissons un JSON valide, cet analyseur retournera une structure d'arbre complète.

Les méthodes Eval, getKeys et getProperty de

JavaScript fournissent des éléments de base pour valider et lire JSON.

couplé à un fonction récursive dans VBA nous pouvons itérer toutes les clés (jusqu'au niveau nth) dans une chaîne JSON. Ensuite, en utilisant une commande D'arbre (utilisé dans cet article) ou un dictionnaire ou même sur une feuille de travail simple, nous pouvons organiser les données JSON comme demandé.

code VBA complet ici.En utilisant les fonctionnalités JavaScript de parsing JSON, en plus de ScriptControl, nous pouvons créer un analyseur dans VBA qui listera chaque point de données à l'intérieur du JSON. Quelle que soit l'imbrication ou la complexité de la structure des données, tant que nous fournissons un JSON valide, cet analyseur retournera une structure arborescente complète.

Les méthodes Eval, getKeys et getProperty de

JavaScript fournissent des éléments de base pour valider et lire JSON.

couplé à une fonction récursive en VBA, nous pouvons itérer toutes les clés (jusqu'au niveau nth) dans une chaîne JSON. Ensuite, en utilisant une commande D'arbre (utilisé dans cet article) ou un dictionnaire ou même sur une feuille de travail simple, nous pouvons organiser les données JSON comme demandé.

code VBA complet ici.

0
répondu cyboashu 2014-11-13 06:41:14

Json n'est rien, mais les cordes de sorte qu'il peut être facilement manipulé si l'on peut manipuler de la bonne façon, peu importe le degré de complexité de la structure. Je ne pense pas qu'il soit nécessaire d'utiliser une bibliothèque externe ou un convertisseur pour faire l'affaire. Voici un exemple où j'ai analysé des données json en utilisant la manipulation de chaîne de caractères.

Sub Json_coder()
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)
        Cells(y, 5) = Split(Split(itm(y), "suite"": """)(1), """")(0)
        Cells(y, 6) = Split(Split(itm(y), "city"": """)(1), """")(0)
        Cells(y, 7) = Split(Split(itm(y), "zipcode"": """)(1), """")(0)
        Cells(y, 8) = Split(Split(itm(y), "phone"": """)(1), """")(0)
        Cells(y, 9) = Split(Split(itm(y), "website"": """)(1), """")(0)
        Cells(y, 10) = Split(Split(Split(itm(y), "company"": ")(1), "name"": """)(1), """")(0)
        Cells(y, 11) = Split(Split(itm(y), "catchPhrase"": """)(1), """")(0)
        Cells(y, 12) = Split(Split(itm(y), "bs"": """)(1), """")(0)
    Next y
End Sub
0
répondu SIM 2017-06-16 08:29:57

c'est le code d'exemple vb6, testé ok,travaux effectués

à partir des bons exemples ci-dessus, j'ai fait des changements et j'ai obtenu ce bon résultat

il peut lire les clés {} et les tableaux []

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
0
répondu Remon Reffat 2017-11-22 14:28:17

formule dans une cellule EXCEL

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

affichages: 22.2

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

affichages: 2222

  • INSTRUCTIONS:
  • Step1. appuyez sur ALT+F11
  • Step2. Insérer - > Module
  • Etape 3. Outils - > Références - > tick Microsoft Script Control 1.0
  • Etape 4. collez ci-dessous.
  • Etape 5. ALT+Q fermer la fenêtre VBA.

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

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
0
répondu hamish 2018-05-09 11:17:55