├── Beta ├── JSON2XML.bas ├── jsJsonParser.cls ├── jsonExt.bas └── simpleJsonJSParser.bas ├── JSON.bas ├── LICENSE └── README.md /Beta/JSON2XML.bas: -------------------------------------------------------------------------------- 1 | Attribute VB_Name = "JSON2XML" 2 | ' JSON2XML (beta) v0.1 3 | ' Copyright (C) 2015-2020 omegastripes 4 | ' omegastripes@yandex.ru 5 | ' https://github.com/omegastripes/VBA-JSON-parser 6 | ' 7 | ' This program is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' This program is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with this program. If not, see . 19 | 20 | Option Explicit 21 | 22 | Sub convertJsonToXmlDomTest() 23 | 24 | ' convert JSON to XML DOM 25 | 26 | ' add references: 27 | ' Microsoft XML, v6.0 28 | ' Microsoft Scripting Runtime 29 | 30 | Dim content As String 31 | ' retrieve json 32 | With New MSXML2.XMLHTTP 33 | .Open "GET", "http://trirand.com/blog/phpjqgrid/examples/jsonp/getjsonp.php?qwery=longorders&rows=20000", True 34 | .Send 35 | Do Until .ReadyState = 4: DoEvents: Loop 36 | content = .ResponseText 37 | End With 38 | saveTextToFile content, ThisWorkbook.Path & "\data.json", "utf-8" 39 | ' ' load json 40 | ' content = loadTextFromFile(ThisWorkbook.Path & "\data.json", "utf-8") 41 | 42 | Dim t 43 | t = Timer 44 | ' extract strings from json body 45 | With CreateObject("VBScript.RegExp") 46 | .Global = True 47 | .MultiLine = True 48 | .IgnoreCase = True 49 | .pattern = "(""|')((?:\\\1|(?!\1).)*)\1" 50 | content = .Replace(content, ChrW(0) & "$2" & ChrW(0)) ' ChrW(0) = vbNullChar 51 | .pattern = "\b([A-Za-z_]\w*)(?=\s*\:)" 52 | content = .Replace(content, ChrW(0) & "$1" & ChrW(0)) 53 | End With 54 | Dim chunks 55 | chunks = Split(content, ChrW(0)) 56 | Dim strings 57 | strings = Array() 58 | If UBound(chunks) > 0 Then 59 | ReDim strings((UBound(chunks) - 1) \ 2) ' 1 - 0, 3 - 1, 5 - 2 60 | Dim i 61 | For i = 1 To UBound(chunks) Step 2 62 | strings((i - 1) \ 2) = chunks(i) 63 | chunks(i) = ChrW(0) 64 | Next 65 | End If 66 | ' unescape json chars and encoding html entities 67 | content = Join(strings, ChrW(0)) 68 | content = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _ 69 | content, _ 70 | "<", "<"), _ 71 | ">", ">"), _ 72 | "&", "&"), _ 73 | "'", "'"), _ 74 | "\""", """), _ 75 | "\\", "\" & ChrW(-1)), _ 76 | "\/", "/"), _ 77 | "\b", Chr(8)), _ 78 | "\f", Chr(12)), _ 79 | "\n", vbLf), _ 80 | "\r", vbCr), _ 81 | "\t", vbTab) 82 | strings = Split(content, "\u") 83 | ' replace unicode chars 84 | For i = 1 To UBound(strings) 85 | Dim u 86 | u = ChrW(("&H" & Left(strings(i), 4)) * 1) 87 | strings(i) = u & Mid(strings(i), 5) 88 | Next 89 | content = Join(strings, "") 90 | content = Replace(content, "\" & ChrW(-1), "\") 91 | strings = Split(content, ChrW(0)) 92 | ' simplify json body 93 | content = Join(chunks, "") 94 | With CreateObject("VBScript.RegExp") 95 | .Global = True 96 | .MultiLine = True 97 | .IgnoreCase = True 98 | .pattern = "\s+" 99 | content = .Replace(content, "") 100 | .pattern = ",,+" 101 | content = .Replace(content, ",") 102 | End With 103 | ' convert json to xml outline 104 | ' With CreateObject("VBScript.RegExp") 105 | ' .Global = True 106 | ' .MultiLine = True 107 | ' .IgnoreCase = True 108 | ' .pattern = "\[," 109 | ' content = .Replace(content, "[") 110 | ' .pattern = "\{," 111 | ' content = .Replace(content, "{") 112 | ' .pattern = ",\]" 113 | ' content = .Replace(content, "]") 114 | ' .pattern = ",\}" 115 | ' content = .Replace(content, "}") 116 | ' .pattern = ":\u0000" 117 | ' content = .Replace(content, """ type=""string"">" & ChrW(0)) 118 | ' .pattern = ":" 119 | ' content = .Replace(content, """>") 120 | ' .pattern = "\{\u0000""" 121 | ' content = .Replace(content, "") 126 | ' .pattern = "\[" 127 | ' content = .Replace(content, "") 128 | ' .pattern = "," 129 | ' content = .Replace(content, "") 130 | ' .pattern = "\]" 131 | ' content = .Replace(content, "") 132 | ' End With 133 | content = Replace(content, "[,", "[") 134 | content = Replace(content, "{,", "{") 135 | content = Replace(content, ",]", "]") 136 | content = Replace(content, ",}", "}") 137 | content = Replace(content, ":" & ChrW(0), """ type=""string"">" & ChrW(0)) 138 | content = Replace(content, ":", """>") 139 | content = Replace(content, "{" & ChrW(0) & """", "") 142 | content = Replace(content, "[", "") 143 | content = Replace(content, ",", "") 144 | content = Replace(content, "]", "") 145 | ' insert strings back to xml structure 146 | chunks = Split(content, ChrW(0)) 147 | For i = 1 To UBound(chunks) 148 | chunks(i) = strings(i - 1) & chunks(i) 149 | Next 150 | content = Join(chunks, "") 151 | ' load xml dom 152 | Dim xml As MSXML2.DOMDocument60 153 | Set xml = New MSXML2.DOMDocument60 154 | xml.LoadXML content 155 | Debug.Print "Elapsed " & Round(Timer - t, 3) & " sec" 156 | isParseXMLSuccess xml 157 | ' 158 | ' processing xml dom 159 | ' 160 | saveTextToFile content, ThisWorkbook.Path & "\result_raw.xml", "utf-8" 161 | ' beautify xml 162 | Dim xml2 As MSXML2.DOMDocument60 163 | Set xml2 = beautifyXML(xml) 164 | saveTextToFile xml2.xml, ThisWorkbook.Path & "\result_beautified.xml", "utf-8" 165 | 166 | End Sub 167 | 168 | Function beautifyXML(xml As MSXML2.DOMDocument60) As MSXML2.DOMDocument60 169 | 170 | Dim writer As New MSXML2.MXXMLWriter60 171 | Dim reader As New MSXML2.SAXXMLReader60 172 | Dim content As String 173 | 174 | writer.Indent = True 175 | writer.omitXMLDeclaration = True 176 | With reader 177 | Set .contentHandler = writer 178 | Set .dtdHandler = writer 179 | Set .errorHandler = writer 180 | .putProperty "http://xml.org/sax/properties/lexical-handler", writer 181 | .putProperty "http://xml.org/sax/properties/declaration-handler", writer 182 | .Parse xml 183 | End With 184 | 'beautifyXML = "" & vbCrLf & writer.Output 185 | content = writer.output 186 | content = IIf(Left(content, 6) <> "" & vbCrLf, "") & content 187 | loadXmlFromString content, beautifyXML, True 188 | 189 | End Function 190 | 191 | Sub loadXmlFromString(content As String, xml As MSXML2.DOMDocument60, success As Boolean) 192 | 193 | Set xml = New MSXML2.DOMDocument60 194 | With xml 195 | .validateOnParse = False 196 | .resolveExternals = False 197 | '.preserveWhiteSpace = True 198 | .setProperty "ProhibitDTD", False 199 | .setProperty "SelectionLanguage", "XPath" 200 | .LoadXML content 201 | '.InsertBefore .createProcessingInstruction("xml", "version=""1.0"" encoding=""utf-8"""), .FirstChild 202 | success = isParseXMLSuccess(xml) 203 | End With 204 | 205 | End Sub 206 | 207 | Function isParseXMLSuccess(xml As MSXML2.DOMDocument60) As Boolean 208 | 209 | With xml.parseError 210 | isParseXMLSuccess = .ErrorCode = 0 211 | If Not isParseXMLSuccess Then 212 | MsgBox _ 213 | "XML parsing error: " & _ 214 | .ErrorCode & ", " & _ 215 | .reason & ", " & _ 216 | "line: " & .Line & ", " & _ 217 | "pos:" & .linepos & ", " & _ 218 | "source: " & .srcText, _ 219 | vbExclamation 220 | End If 221 | End With 222 | 223 | End Function 224 | 225 | Function loadTextFromFile(filePath, charset) 226 | 227 | With CreateObject("ADODB.Stream") 228 | .Type = 1 ' TypeBinary 229 | .Open 230 | .LoadFromFile filePath 231 | .Position = 0 232 | .Type = 2 ' adTypeText 233 | .charset = charset 234 | loadTextFromFile = .ReadText 235 | .Close 236 | End With 237 | 238 | End Function 239 | 240 | Sub saveTextToFile(content, filePath, charset) 241 | 242 | smartCreateFolder CreateObject("Scripting.FileSystemObject").GetParentFolderName(filePath) 243 | With CreateObject("ADODB.Stream") 244 | .Type = 2 ' adTypeText 245 | .Open 246 | .charset = charset 247 | .WriteText content 248 | .Position = 0 249 | .Type = 1 ' TypeBinary 250 | .SaveToFile filePath, 2 251 | .Close 252 | End With 253 | 254 | End Sub 255 | 256 | Sub smartCreateFolder(folder) 257 | 258 | With CreateObject("Scripting.FileSystemObject") 259 | If Not .FolderExists(folder) Then 260 | smartCreateFolder .GetParentFolderName(folder) 261 | .CreateFolder folder 262 | End If 263 | End With 264 | 265 | End Sub 266 | 267 | 268 | -------------------------------------------------------------------------------- /Beta/jsJsonParser.cls: -------------------------------------------------------------------------------- 1 | VERSION 1.0 CLASS 2 | BEGIN 3 | MultiUse = -1 'True 4 | END 5 | Attribute VB_Name = "jsJsonParser" 6 | Attribute VB_GlobalNameSpace = False 7 | Attribute VB_Creatable = False 8 | Attribute VB_PredeclaredId = False 9 | Attribute VB_Exposed = False 10 | ' Douglas Crockford json2.js implementation for VBA 11 | ' version 2021-01-01 12 | ' https://github.com/douglascrockford/JSON-js/blob/master/json2.js 13 | ' 14 | ' jsJsonParser (beta) v0.1.2 15 | ' Copyright (C) 2021 omegastripes 16 | ' omegastripes@yandex.ru 17 | ' https://github.com/omegastripes/VBA-JSON-parser 18 | ' 19 | ' This program is free software: you can redistribute it and/or modify 20 | ' it under the terms of the GNU General Public License as published by 21 | ' the Free Software Foundation, either version 3 of the License, or 22 | ' (at your option) any later version. 23 | ' 24 | ' This program is distributed in the hope that it will be useful, 25 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 26 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 27 | ' GNU General Public License for more details. 28 | ' 29 | ' You should have received a copy of the GNU General Public License 30 | ' along with this program. If not, see . 31 | 32 | Option Explicit 33 | 34 | Private document As Object 35 | Private jsonParser As Object 36 | Private getProp As Object 37 | Private getType As Object 38 | Private copyDict As Object 39 | 40 | Private Sub Class_Initialize() 41 | 42 | Set document = CreateObject("htmlfile") 43 | document.Write "'" 44 | With document.parentWindow 45 | .execScript jsCode() 46 | Set jsonParser = .JSON 47 | Set getProp = .getProp 48 | Set getType = .getType 49 | Set copyDict = .copyDict 50 | End With 51 | 52 | End Sub 53 | 54 | Public Property Get jsGetProp() ' As JScriptTypeInfo 55 | 56 | Set jsGetProp = getProp 57 | 58 | End Property 59 | 60 | Public Property Get jsGetType() ' As JScriptTypeInfo 61 | 62 | Set jsGetType = getType 63 | 64 | End Property 65 | 66 | Public Function parseToJs(sample, Optional success) 67 | 68 | On Error Resume Next 69 | Set parseToJs = jsonParser.parse(sample) ': Dim parse ' keep lower case 70 | success = Err.Number = 0 71 | If Not success Then 72 | Set parseToJs = Nothing 73 | End If 74 | 75 | End Function 76 | 77 | Public Function parseToVb(Optional sample, Optional jsJsonData, Optional result, Optional success) 78 | 79 | If Not IsMissing(sample) Then 80 | Set jsJsonData = parseToJs(sample) 81 | End If 82 | On Error Resume Next 83 | If jsJsonData Is Nothing Then 84 | success = False 85 | Else 86 | Dim vbaJsonObject 87 | repack jsJsonData, vbaJsonObject 88 | success = Err.Number = 0 89 | If success Then 90 | If IsObject(vbaJsonObject) Then 91 | Set parseToVb = vbaJsonObject 92 | Set result = vbaJsonObject 93 | Else 94 | parseToVb = vbaJsonObject 95 | result = vbaJsonObject 96 | End If 97 | Else 98 | parseToVb = Empty 99 | result = Empty 100 | Set jsJsonData = Nothing 101 | End If 102 | End If 103 | 104 | End Function 105 | 106 | Public Function stringify(jsJsonData, spacer) ' jsJsonData As JScriptTypeInfo 107 | 108 | On Error Resume Next 109 | stringify = jsonParser.stringify(jsJsonData, "", spacer) ': Dim stringify ' keep lower case 110 | 111 | End Function 112 | 113 | Private Sub repack(source, result) 114 | 115 | Select Case getType(source) 116 | Case "array" 117 | result = copyDict(source, New Dictionary).items 118 | Dim i 119 | For i = 0 To UBound(result) 120 | Dim ret 121 | repack result(i), ret 122 | If IsObject(ret) Then 123 | Set result(i) = ret 124 | Else 125 | result(i) = ret 126 | End If 127 | Next 128 | Case "object" 129 | Set result = copyDict(source, New Dictionary) 130 | For Each i In result 131 | repack result(i), ret 132 | If IsObject(ret) Then 133 | Set result(i) = ret 134 | Else 135 | result(i) = ret 136 | End If 137 | Next 138 | Case "string" 139 | result = CStr(source) 140 | Case "number" 141 | result = CDbl(source) 142 | Case "boolean" 143 | result = CBool(source) 144 | Case "null" 145 | result = Null 146 | End Select 147 | 148 | End Sub 149 | 150 | Private Function jsCode() 151 | 152 | ' credits 153 | ' github repo 154 | ' https://github.com/douglascrockford/JSON-js/blob/master/json2.js 155 | ' source json2.js 2017-06-12 156 | ' https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js 157 | ' js -minifier 158 | ' http://beautifytools.com/javascript-minifier.php 159 | 160 | jsCode = Replace( _ 161 | "function getProp(t,e){return t[e]}function getType(t){switch(typeof t){case`string`:case`number`:case`boolean`:case`null`:return typeof t;case`object`:if(!t)return`null`;if(`[object Array]`===Object.prototype.toString.apply(t))return`array`}return`ob" & _ 162 | "ject`}function copyDict(t,e){for(var r in t)e.Add(r,t[r]);return e}`object`!=typeof JSON&&(JSON={}),function(){`use strict`;function f(t){return 10>t?`0`+t:t}function this_value(){return this.valueOf()}function quote(t){return rx_escapable.lastIndex=" & _ 163 | "0,rx_escapable.test(t)?'`'+t.replace(rx_escapable,function(t){var e=meta[t];return`string`==typeof e?e:`\\u`+(`0000`+t.charCodeAt(0).toString(16)).slice(-4)})+'`':'`'+t+'`'}function str(t,e){var r,n,o,u,f,a=gap,i=e[t];switch(i&&`object`==typeof i&&`f" & _ 164 | "unction`==typeof i.toJSON&&(i=i.toJSON(t)),`function`==typeof rep&&(i=rep.call(e,t,i)),typeof i){case`string`:return quote(i);case`number`:return isFinite(i)?String(i):`null`;case`boolean`:case`null`:return String(i);case`object`:if(!i)return`null`;i" & _ 165 | "f(gap+=indent,f=[],`[object Array]`===Object.prototype.toString.apply(i)){for(u=i.length,r=0;u>r;r+=1)f[r]=str(r,i)||`null`;return o=0===f.length?`[]`:gap?`[\n`+gap+f.join(`,\n`+gap)+`\n`+a+`]`:`[`+f.join(`,`)+`]`,gap=a,o}if(rep&&`object`==typeof rep" & _ 166 | ")for(u=rep.length,r=0;u>r;r+=1)`string`==typeof rep[r]&&(n=rep[r],o=str(n,i),o&&f.push(quote(n)+(gap?`: `:`:`)+o));else for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(o=str(n,i),o&&f.push(quote(n)+(gap?`: `:`:`)+o));return o=0===f.length?`{}`" & _ 167 | ":gap?`{\n`+gap+f.join(`,\n`+gap)+`\n`+a+`}`:`{`+f.join(`,`)+`}`,gap=a,o}}var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:[`\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/`[^`\\\n\r]*`|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/" & _ 168 | "g,rx_escapable=/[\\`\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\u" & _ 169 | "fff0-\uffff]/g;`function`!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+`-`+f(this.getUTCMonth()+1)+`-`+f(this.getUTCDate())+`T`+f(this.getUTCHours())+`:`+f(this.getUTCMinutes()" & _ 170 | ")+`:`+f(this.getUTCSeconds())+`Z`:null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value);var gap,indent,meta,rep;`function`!=typeof JSON.stringify&&(meta={`\b`:`\\b`,` `:`\\t`,`\n`:`\\n`,`\f`:" & _ 171 | "`\\f`,`\r`:`\\r`,'`':'\\`',`\\`:`\\\\`},JSON.stringify=function(t,e,r){var n;if(gap=``,indent=``,`number`==typeof r)for(n=0;r>n;n+=1)indent+=` `;else`string`==typeof r&&(indent=r);if(rep=e,e&&`function`!=typeof e&&(`object`!=typeof e||`number`!=typeo" & _ 172 | "f e.length))throw new Error(`JSON.stringify`);return str(``,{``:t})}),`function`!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(t,e){var r,n,o=t[e];if(o&&`object`==typeof o)for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(" & _ 173 | "n=walk(o,r),void 0!==n?o[r]=n:delete o[r]);return reviver.call(t,e,o)}var j;if(text=String(text),rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(t){return`\\u`+(`0000`+t.charCodeAt(0).toString(16)).slice(-4)" & _ 174 | "})),rx_one.test(text.replace(rx_two,`@`).replace(rx_three,`]`).replace(rx_four,``)))return j=eval(`(`+text+`)`),`function`==typeof reviver?walk({``:j},``):j;throw new SyntaxError(`JSON.parse`)})}();var json=JSON;", _ 175 | "`", """" _ 176 | ) 177 | 178 | End Function 179 | -------------------------------------------------------------------------------- /Beta/jsonExt.bas: -------------------------------------------------------------------------------- 1 | Attribute VB_Name = "jsonExt" 2 | ' Extension (beta) v0.1.103 for VBA JSON parser, Backus-Naur form JSON parser based on RegEx v1.7.21 3 | ' Copyright (C) 2015-2020 omegastripes 4 | ' omegastripes@yandex.ru 5 | ' https://github.com/omegastripes/VBA-JSON-parser 6 | ' 7 | ' This program is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' This program is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with this program. If not, see . 19 | 20 | Option Explicit 21 | 22 | Private chunks As Dictionary 23 | Private headerList As Dictionary 24 | Private data2dArray() As Variant 25 | Private i As Long 26 | Private skipNew As Boolean 27 | Private ascend As Boolean 28 | 29 | Sub toArray(jsonData As Variant, body() As Variant, head() As Variant, Optional skipNewNames As Boolean = False) 30 | 31 | ' Input: 32 | ' jsonData - Array or Object which contains rows data 33 | ' head - Empty array or array of explicitly set properties names (property name for properties names is "#") 34 | ' skipNewNames - Behavior of processing new properties names, uses head only if True 35 | ' Output: 36 | ' body - 2d array representing JSON data 37 | ' head - 1d array of property names 38 | 39 | skipNew = skipNewNames 40 | Set headerList = New Dictionary 41 | Dim field As Variant 42 | Dim j As Long 43 | If safeUBound(head) >= 0 Then 44 | For Each field In head 45 | If Not headerList.exists(field) Then headerList(field) = headerList.count 46 | Next 47 | j = headerList.count - 1 48 | Else 49 | j = 0 50 | End If 51 | Select Case VarType(jsonData) 52 | Case vbObject 53 | If jsonData.count > 0 Then 54 | If Not skipNew Then 55 | headerList("#") = 0 56 | End If 57 | ReDim data2dArray(0 To jsonData.count - 1, 0 To j) 58 | i = 0 59 | For Each field In jsonData.keys() 60 | If skipNew Then 61 | If headerList.exists("#") Then 62 | j = headerList("#") 63 | data2dArray(i, j) = field 64 | End If 65 | Else 66 | data2dArray(i, 0) = field 67 | End If 68 | toArrayElement jsonData(field), "" 69 | i = i + 1 70 | Next 71 | Else 72 | ReDim data2dArray(0 To 0, 0 To j) 73 | End If 74 | Case Is >= vbArray 75 | If UBound(jsonData) >= 0 Then 76 | ReDim data2dArray(0 To UBound(jsonData), 0 To j) 77 | For i = 0 To UBound(jsonData) 78 | toArrayElement jsonData(i), "" 79 | Next 80 | Else 81 | ReDim data2dArray(0 To 0, 0 To j) 82 | End If 83 | Case Else 84 | ReDim data2dArray(0 To 0, 0 To j) 85 | data2dArray(0, 0) = jsonData 86 | End Select 87 | head = headerList.keys() 88 | Set headerList = Nothing 89 | body = data2dArray 90 | Erase data2dArray 91 | 92 | End Sub 93 | 94 | Private Sub toArrayElement(element As Variant, fieldName As String) 95 | 96 | Dim j As Long 97 | Select Case VarType(element) 98 | Case vbObject ' Collection of objects 99 | Dim field As Variant 100 | For Each field In element.keys() 101 | toArrayElement element(field), fieldName & IIf(fieldName = "", "", ".") & field 102 | Next 103 | Case Is >= vbArray ' Collection of arrays 104 | For j = 0 To UBound(element) 105 | toArrayElement element(j), fieldName & "[" & j & "]" 106 | Next 107 | Case Else 108 | If skipNew Then 109 | If headerList.exists(fieldName) Then 110 | j = headerList(fieldName) 111 | data2dArray(i, j) = element 112 | End If 113 | Else 114 | If Not headerList.exists(fieldName) Then 115 | headerList(fieldName) = headerList.count 116 | If UBound(data2dArray, 2) < headerList.count - 1 Then ReDim Preserve data2dArray(0 To UBound(data2dArray, 1), 0 To headerList.count - 1) 117 | End If 118 | j = headerList(fieldName) 119 | data2dArray(i, j) = element 120 | End If 121 | End Select 122 | 123 | End Sub 124 | 125 | Public Function flatten(jsonData) 126 | 127 | Set chunks = New Dictionary 128 | flattenElement jsonData, "" 129 | Set flatten = chunks 130 | Set chunks = Nothing 131 | 132 | End Function 133 | 134 | Private Sub flattenElement(element As Variant, property As String) 135 | 136 | 137 | Select Case True 138 | Case TypeOf element Is Dictionary 139 | If element.count > 0 Then 140 | Dim key 141 | For Each key In element.keys() 142 | flattenElement element(key), IIf(property <> "", property & "." & key, key) 143 | Next 144 | End If 145 | Case IsObject(element) 146 | Case IsArray(element) 147 | Dim i As Long 148 | For i = 0 To UBound(element) 149 | flattenElement element(i), property & "[" & i & "]" 150 | Next 151 | Case Else 152 | chunks(property) = element 153 | End Select 154 | 155 | End Sub 156 | 157 | Public Sub nestedArraysToArray(body, head, data, success) 158 | 159 | ' Input: 160 | ' body - nested 1d arrays representing table data 161 | ' head - 1d array of property names 162 | ' Output: 163 | ' data - resulting array with JSON data 164 | ' success - false if head and nested array sizes not match 165 | 166 | Dim buffer 167 | buffer = Array() 168 | Dim i 169 | For i = 0 To UBound(body) 170 | Dim entry 171 | entry = body(i) 172 | success = UBound(head) = UBound(entry) 173 | If Not success Then Exit For 174 | Dim props 175 | Set props = New Dictionary 176 | Dim j 177 | For j = 0 To UBound(head) 178 | props(head(j)) = entry(j) 179 | Next 180 | pushItem buffer, props 181 | Next 182 | data = buffer 183 | 184 | End Sub 185 | 186 | Public Sub filterElements(root, conditions, inclusive, result, success) 187 | 188 | ' filtering elements of root array or object 189 | ' input: 190 | ' root - source array or object which elements to be filtered 191 | ' conditions - condition array or nested condition arrays that finally must be evaluated as boolean 192 | ' inclusive - element will be added to result if 193 | ' evaluation is true and inclusive is true 194 | ' evaluation is false or n/a and inclusive is false 195 | ' output: 196 | ' result - array or object with filtered elements 197 | ' success - false if root isn't array or object 198 | ' condition array description: 199 | ' supported operations 200 | ' retrieve element by path relative to root as scalar value or any other JSON entity 201 | ' = Array("value", ) 202 | ' - string, expression in JS format, path relative to element of root array or object 203 | ' example: Array("value", "[0].volume") 204 | ' return count of elements in root by path as number 205 | ' = Array("count", ) 206 | ' - string, expression in JS format, path relative to element of root array or object 207 | ' example: Array("count", ".shape.points") 208 | ' check if element exists by path relative to root as boolean 209 | ' = Array("exists", ) 210 | ' - string, expression in JS format, path relative to element of root array or object 211 | ' example: Array("exists", ".items[0].restrictions") 212 | ' compare two values and return result as boolean 213 | ' = Array(, , ) 214 | ' - string: "=", "<>", ">", ">=", "<", "<=" 215 | ' - scalar, or nested evaluated as scalar 216 | ' example: Array(">=", Array("value", ".data.volume"), 100) - evaluation is true if .data.volume >= 100 217 | ' check if value belongs to interval specified by two values and return result as boolean 218 | ' = Array(, , , ) 219 | ' - string: "[]", "[)", "(]", "()" 220 | ' square brackets mean the end point is included, round parentheses mean it's excluded 221 | ' - scalar, or nested evaluated as scalar 222 | ' example: Array("[]", Array("value", "."), 0, 100) - evaluation is true if element value itself >= 0 and <= 100 223 | ' boolean unary 224 | ' = Array("not", ) 225 | ' - boolean, or nested evaluated as boolean 226 | ' example: Array("not", Array("[]", Array("value", "."), 0, 100)) - evaluation is true if element value itself < 0 or > 100 227 | ' "not" operation can be concatenated with any other operation which returns boolean 228 | ' examples: 229 | ' Array("not exists", ".items[0].restrictions") 230 | ' Array("not >=", Array("value", ".data.volume"), 100) 231 | ' Array("not ()", Array("value", "."), 0, 100) 232 | ' boolean binary 233 | ' = Array(, , ) 234 | ' - string: "or", "and", "xor" 235 | ' - boolean, or nested evaluated as boolean 236 | ' example: Array("and", Array("[]", Array("value", ".volume"), 0, 100), Array(">", Array("value", ".height"), 50)) 237 | ' "or", "and" operations actually accept > 2 arguments, "or" provides lazy evaluation 238 | ' = Array(, , , ...) 239 | ' example: 240 | ' Array("and", Array("[]", Array("value", ".volume"), 0, 100), Array(">", Array("value", ".height"), 50), Array("<", Array("count", ".specification.items"), 10)) 241 | ' the same example serialized: 242 | ' [ 243 | ' "and", 244 | ' [ 245 | ' "[]", 246 | ' [ 247 | ' "value", 248 | ' ".volume" 249 | ' ], 250 | ' 0, 251 | ' 100 252 | ' ], 253 | ' [ 254 | ' ">", 255 | ' [ 256 | ' "value", 257 | ' ".height" 258 | ' ], 259 | ' 50 260 | ' ], 261 | ' [ 262 | ' "<", 263 | ' [ 264 | ' "count", 265 | ' ".specification.items" 266 | ' ], 267 | ' 10 268 | ' ] 269 | ' ] 270 | Dim data 271 | Dim k 272 | Dim ret 273 | Dim decision 274 | Dim ok 275 | If IsArray(root) Then 276 | data = Array() 277 | For k = 0 To safeUBound(root) 278 | evaluateExpression root(k), conditions, ret, ok 279 | decision = False 280 | Select Case False 281 | Case ok 282 | Case VarType(ret) = vbBoolean 283 | Case ret 284 | Case Else 285 | decision = True 286 | End Select 287 | If decision Xor Not inclusive Then 288 | pushItem data, root(k) 289 | End If 290 | Next 291 | result = data 292 | success = True 293 | ElseIf TypeOf root Is Dictionary Then 294 | Set data = New Dictionary 295 | For Each k In root.keys() 296 | evaluateExpression root(k), conditions, ret, ok 297 | decision = False 298 | Select Case False 299 | Case ok 300 | Case VarType(ret) = vbBoolean 301 | Case ret 302 | Case Else 303 | decision = True 304 | End Select 305 | If decision Xor Not inclusive Then 306 | If IsObject(root(k)) Then 307 | Set data(k) = root(k) 308 | Else 309 | data(k) = root(k) 310 | End If 311 | End If 312 | Next 313 | Set result = data 314 | success = True 315 | Else 316 | success = False 317 | End If 318 | 319 | End Sub 320 | 321 | Public Sub groupElements(root, path, full, result, success) 322 | 323 | ' grouping elements of root array or object 324 | ' input: 325 | ' root - source array or object which elements to be grouped 326 | ' path - string, expression in JS format, path relative to element of root array or object to entity it grouped by, or array of path components 327 | ' full - true to create null group for elements having no specified path 328 | ' output: 329 | ' result - dictionary with sorted elements with group names as keys 330 | ' success - false if root isn't array or object 331 | 332 | Dim k 333 | Dim entry 334 | Dim exists 335 | If IsArray(root) Then 336 | Set result = New Dictionary 337 | Dim buffer 338 | buffer = Array() 339 | For k = 0 To safeUBound(root) 340 | selectElement root(k), path, entry, exists 341 | If exists Or full Then 342 | If Not exists Then 343 | entry = Null 344 | End If 345 | If Not result.exists(entry) Then 346 | result(entry) = result.count 347 | jsonExt.pushItem buffer, Array() 348 | End If 349 | jsonExt.pushItem buffer(result(entry)), root(k) 350 | End If 351 | Next 352 | For Each k In result.keys() 353 | result(k) = buffer(result(k)) 354 | Next 355 | success = True 356 | ElseIf TypeOf root Is Dictionary Then 357 | Set result = New Dictionary 358 | For Each k In root.keys() 359 | selectElement root(k), path, entry, exists 360 | If exists Or full Then 361 | If Not exists Then 362 | entry = Null 363 | End If 364 | If Not result.exists(entry) Then 365 | Set result(entry) = New Dictionary 366 | End If 367 | If IsObject(root(k)) Then 368 | Set result(entry)(k) = root(k) 369 | Else 370 | result(entry)(k) = root(k) 371 | End If 372 | End If 373 | Next 374 | success = True 375 | Else 376 | success = False 377 | End If 378 | 379 | End Sub 380 | 381 | Private Sub evaluateExpression(root, expr, result, success) 382 | 383 | Dim operation 384 | operation = LCase(expr(0)) 385 | Dim value1 386 | Dim value2 387 | Dim value3 388 | Dim ok 389 | If Left(operation, 4) = "not " Then 390 | Dim subexpr 391 | subexpr = expr 392 | subexpr(0) = Mid(operation, 5) 393 | evaluateExpression root, subexpr, value1, ok 394 | If ok And VarType(value1) = vbBoolean Then 395 | result = Not value1 396 | success = True 397 | Exit Sub 398 | End If 399 | End If 400 | success = False 401 | Dim exists 402 | Select Case operation 403 | Case "" 404 | Case "value" 405 | selectElement root, expr(1), value1, exists 406 | success = exists 407 | If Not success Then 408 | Exit Sub 409 | End If 410 | assign value1, result 411 | Case "count" 412 | selectElement root, expr(1), value1, exists 413 | success = exists 414 | If success Then 415 | If IsArray(value1) Then 416 | result = UBound(value1) + 1 417 | ElseIf TypeOf root Is Dictionary Then 418 | result = value1.count 419 | Else 420 | success = False 421 | End If 422 | End If 423 | Case "exists" 424 | selectElement root, expr(1), value1, exists 425 | result = exists 426 | success = True 427 | Case "=", "<>", ">", ">=", "<", "<=", "[]", "[)", "(]", "()" 428 | If isScalar(expr(1)) Then 429 | value1 = expr(1) 430 | Else 431 | evaluateExpression root, expr(1), value1, ok 432 | If Not (ok And isScalar(value1)) Then 433 | Exit Sub 434 | End If 435 | End If 436 | If isScalar(expr(2)) Then 437 | value2 = expr(2) 438 | Else 439 | evaluateExpression root, expr(2), value2, ok 440 | If Not (ok And isScalar(value2)) Then 441 | Exit Sub 442 | End If 443 | End If 444 | Select Case operation 445 | Case "[]", "[)", "(]", "()" 446 | If isScalar(expr(3)) Then 447 | value3 = expr(3) 448 | Else 449 | evaluateExpression root, expr(3), value3, ok 450 | If Not (ok And isScalar(value3)) Then 451 | Exit Sub 452 | End If 453 | End If 454 | End Select 455 | Select Case operation 456 | Case "=" 457 | result = CBool(value1 = value2) 458 | Case "<>" 459 | result = CBool(value1 <> value2) 460 | Case ">" 461 | result = CBool(value1 > value2) 462 | Case ">=" 463 | result = CBool(value1 >= value2) 464 | Case "<" 465 | result = CBool(value1 < value2) 466 | Case "<=" 467 | result = CBool(value1 <= value2) 468 | Case "[]" 469 | result = CBool((value1 >= value2) And (value1 <= value3)) 470 | Case "[)" 471 | result = CBool((value1 >= value2) And (value1 < value3)) 472 | Case "(]" 473 | result = CBool((value1 > value2) And (value1 <= value3)) 474 | Case "()" 475 | result = CBool((value1 > value2) And (value1 < value3)) 476 | End Select 477 | success = True 478 | Case "or", "and" 479 | value2 = True 480 | Dim i 481 | For i = 1 To UBound(expr) 482 | If VarType(expr(i)) = vbBoolean Then 483 | value1 = expr(i) 484 | Else 485 | evaluateExpression root, expr(i), value1, ok 486 | If Not (ok And VarType(value1) = vbBoolean) Then 487 | Exit Sub 488 | End If 489 | End If 490 | If value1 And operation = "or" Then 491 | result = True 492 | success = True 493 | Exit Sub 494 | End If 495 | value2 = value2 And value1 496 | If Not value2 And operation = "and" Then 497 | result = False 498 | success = True 499 | Exit Sub 500 | End If 501 | Next 502 | If operation = "or" Then 503 | result = False 504 | Else 505 | result = True 506 | End If 507 | success = True 508 | Case "xor", "not" 509 | If VarType(expr(1)) = vbBoolean Then 510 | value1 = expr(1) 511 | Else 512 | evaluateExpression root, expr(1), value1, ok 513 | If Not (ok And VarType(value1) = vbBoolean) Then 514 | Exit Sub 515 | End If 516 | End If 517 | If operation = "not" Then 518 | result = Not value1 519 | Else 520 | If VarType(expr(2)) = vbBoolean Then 521 | value2 = expr(2) 522 | Else 523 | evaluateExpression root, expr(2), value2, ok 524 | If Not (ok And VarType(value2) = vbBoolean) Then 525 | Exit Sub 526 | End If 527 | End If 528 | result = value1 And value2 529 | End If 530 | success = True 531 | End Select 532 | 533 | End Sub 534 | 535 | Public Sub sort(root, path, ascending, result) 536 | 537 | ' sorting elements of root array or object 538 | ' input: 539 | ' root - source array or object which elements to be sorted 540 | ' path - string, expression in JS format, path relative to element of root array or object to entity it sorted by, or array of path components 541 | ' ascending - sorting direction 542 | ' output: 543 | ' result - array or object with sorted elements 544 | 545 | ascend = ascending 546 | Dim sample() 547 | sample = Array() 548 | Dim index() 549 | index = Array() 550 | Dim data 551 | Dim last 552 | Dim k 553 | Dim entry 554 | Dim exists 555 | Dim i 556 | If IsArray(root) Then 557 | data = Array() 558 | last = safeUBound(root) 559 | If last >= 0 Then 560 | ReDim sample(last) 561 | ReDim index(last) 562 | ReDim data(last) 563 | For k = 0 To last 564 | index(k) = k 565 | sample(k) = Null 566 | selectElement root(k), path, entry, exists 567 | Select Case False 568 | Case exists 569 | Case Not IsEmpty(entry) 570 | Case isScalar(entry) 571 | Case Else 572 | sample(k) = entry 573 | End Select 574 | Next 575 | quickSortIndex sample, index 576 | For k = 0 To last 577 | i = index(k) 578 | If IsObject(root(i)) Then 579 | Set data(k) = root(i) 580 | Else 581 | data(k) = root(i) 582 | End If 583 | Next 584 | End If 585 | result = data 586 | ElseIf TypeOf root Is Dictionary Then 587 | Set data = New Dictionary 588 | Dim keys 589 | keys = root.keys() 590 | last = UBound(keys) 591 | If last >= 0 Then 592 | ReDim sample(last) 593 | ReDim index(last) 594 | For k = 0 To last 595 | index(k) = k 596 | sample(k) = Null 597 | selectElement root(keys(k)), path, entry, exists 598 | Select Case False 599 | Case exists 600 | Case Not IsEmpty(entry) 601 | Case isScalar(entry) 602 | Case Else 603 | sample(k) = entry 604 | End Select 605 | Next 606 | quickSortIndex sample, index 607 | For k = 0 To last 608 | i = index(k) 609 | Dim key 610 | key = keys(i) 611 | Dim temp 612 | If IsObject(root(key)) Then 613 | Set temp = root(key) 614 | Set data(key) = temp 615 | Else 616 | temp = root(key) 617 | data(key) = temp 618 | End If 619 | Next 620 | End If 621 | Set result = data 622 | Else 623 | assign root, result 624 | End If 625 | 626 | End Sub 627 | 628 | Private Sub quickSortIndex(sample, index) 629 | 630 | ' https://rosettacode.org/wiki/Sorting_algorithms/Quicksort 631 | Dim last As Long 632 | last = UBound(index) 633 | If last > 0 Then 634 | Dim ltArray 635 | ltArray = Array() 636 | Dim eqArray 637 | eqArray = Array() 638 | Dim gtArray 639 | gtArray = Array() 640 | Dim p As Long 641 | p = Int((last + 1) / 2) 642 | Dim pivot 643 | pivot = sample(index(p)) 644 | Dim i As Long 645 | For i = 0 To last 646 | Dim elt 647 | elt = sample(index(i)) 648 | Dim gtCheck 649 | Dim ltCheck 650 | If ascend Then 651 | gtCheck = elt > pivot 652 | ltCheck = elt < pivot 653 | Else 654 | gtCheck = elt < pivot 655 | ltCheck = elt > pivot 656 | End If 657 | If gtCheck Then 658 | ReDim Preserve gtArray(UBound(gtArray) + 1) 659 | gtArray(UBound(gtArray)) = index(i) 660 | ElseIf ltCheck Then 661 | ReDim Preserve ltArray(UBound(ltArray) + 1) 662 | ltArray(UBound(ltArray)) = index(i) 663 | ElseIf elt = pivot Then 664 | ReDim Preserve eqArray(UBound(eqArray) + 1) 665 | eqArray(UBound(eqArray)) = index(i) 666 | Else 667 | If Not IsNull(pivot) Then ' null > pivot 668 | ReDim Preserve gtArray(UBound(gtArray) + 1) 669 | gtArray(UBound(gtArray)) = index(i) 670 | ElseIf Not IsNull(elt) Then ' elt < null 671 | ReDim Preserve ltArray(UBound(ltArray) + 1) 672 | ltArray(UBound(ltArray)) = index(i) 673 | Else ' null = null 674 | ReDim Preserve eqArray(UBound(eqArray) + 1) 675 | eqArray(UBound(eqArray)) = index(i) 676 | End If 677 | End If 678 | Next 679 | quickSortIndex sample, ltArray 680 | quickSortIndex sample, gtArray 681 | p = 0 682 | For i = 0 To UBound(ltArray) 683 | index(p) = ltArray(i) 684 | p = p + 1 685 | Next 686 | For i = 0 To UBound(eqArray) 687 | index(p) = eqArray(i) 688 | p = p + 1 689 | Next 690 | For i = 0 To UBound(gtArray) 691 | index(p) = gtArray(i) 692 | p = p + 1 693 | Next 694 | End If 695 | 696 | End Sub 697 | 698 | Public Sub selectElement(root, path, entry, exists) 699 | 700 | ' retrieve entity from root array or object by relative path 701 | ' input: 702 | ' root - source array or object entity to be retrieved from 703 | ' path - string, expression in JS format, path relative to root array or object, or array of path components 704 | ' output: 705 | ' path - array of path components 706 | ' entry - destination entity retrieved from root by relative path 707 | ' exists - return false if destination entity doesn't exists or path is invalid 708 | 709 | Dim elt 710 | Dim i 711 | If Not IsArray(path) Then 712 | Dim parts 713 | If path = "" Then 714 | parts = Array() 715 | exists = True 716 | Else 717 | Dim elts 718 | elts = Split(Replace(Replace(Replace(path, ".", "|."), "[", "|["), "|.|[", "|.["), "|") 719 | ReDim parts(UBound(elts) - 1) 720 | If elts(0) <> "" Then Exit Sub 721 | For i = 1 To UBound(elts) 722 | exists = False 723 | elt = elts(i) 724 | If Left(elt, 1) = "." Then 725 | parts(i - 1) = Mid(elt, 2) 726 | ElseIf Left(elt, 1) = "[" And Right(elt, 1) = "]" Then 727 | elt = Mid(elt, 2, Len(elt) - 2) 728 | If IsNumeric(elt) Then 729 | parts(i - 1) = CLng(elt) 730 | Else 731 | Exit For 732 | End If 733 | Else 734 | Exit For 735 | End If 736 | exists = True 737 | Next 738 | End If 739 | If Not exists Then Exit Sub 740 | path = parts 741 | End If 742 | assign root, entry 743 | exists = True 744 | For i = 0 To UBound(path) 745 | exists = False 746 | elt = path(i) 747 | If elt = "" Then 748 | exists = True 749 | Exit For 750 | End If 751 | If IsArray(entry) Then 752 | If Not VarType(elt) = vbLong Then Exit For 753 | If elt < LBound(entry) Or elt > UBound(entry) Then Exit For 754 | ElseIf TypeOf entry Is Dictionary Then 755 | If Not entry.exists(elt) Then Exit For 756 | Else 757 | Exit For 758 | End If 759 | If IsObject(entry(elt)) Then 760 | Set entry = entry(elt) 761 | Else 762 | entry = entry(elt) 763 | End If 764 | exists = True 765 | Next 766 | 767 | End Sub 768 | 769 | Public Sub joinSubDicts(acc, src, Optional addNew = True) 770 | 771 | If Not (TypeOf acc Is Dictionary And TypeOf src Is Dictionary) Then 772 | Exit Sub 773 | End If 774 | Dim key 775 | For Each key In src.keys() 776 | If TypeOf src(key) Is Dictionary Then 777 | Dim srcSubDict 778 | Set srcSubDict = src(key) 779 | Dim accSubDict 780 | Set accSubDict = Nothing 781 | If acc.exists(key) Then 782 | If TypeOf acc(key) Is Dictionary Then 783 | Set accSubDict = acc(key) 784 | End If 785 | End If 786 | If accSubDict Is Nothing Then 787 | Set accSubDict = New Dictionary 788 | Set acc(key) = accSubDict 789 | End If 790 | joinDicts accSubDict, srcSubDict, addNew 791 | End If 792 | Next 793 | 794 | End Sub 795 | 796 | Public Sub joinDicts(acc, src, Optional addNew = True) 797 | 798 | If Not (TypeOf acc Is Dictionary And TypeOf src Is Dictionary) Then 799 | Exit Sub 800 | End If 801 | Dim key 802 | Dim temp 803 | If addNew Then 804 | For Each key In src.keys() 805 | If IsObject(src(key)) Then 806 | Set temp = src(key) 807 | Set acc(key) = temp 808 | Else 809 | temp = src(key) 810 | acc(key) = temp 811 | End If 812 | Next 813 | Else 814 | For Each key In src.keys() 815 | If acc.exists(key) Then 816 | If IsObject(src(key)) Then 817 | Set temp = src(key) 818 | Set acc(key) = temp 819 | Else 820 | temp = src(key) 821 | acc(key) = temp 822 | End If 823 | End If 824 | Next 825 | End If 826 | 827 | End Sub 828 | 829 | Public Sub slice(src, Optional result, Optional ByVal a, Optional ByVal b) 830 | 831 | Dim m As Long 832 | If IsArray(src) Then 833 | m = UBound(src) 834 | ElseIf TypeOf src Is Dictionary Then 835 | m = src.count - 1 836 | End If 837 | If IsMissing(a) Then 838 | a = 0 839 | End If 840 | If IsMissing(b) Then 841 | b = m 842 | End If 843 | Dim temp 844 | Dim i 845 | Dim d As Long 846 | If Not (IsNumeric(a) And IsNumeric(b)) Then 847 | If Not IsMissing(result) Then 848 | assign src, result 849 | End If 850 | Exit Sub 851 | End If 852 | Dim void As Boolean 853 | Dim full As Boolean 854 | If a < 0 And b < 0 Or a > m And b > m Then 855 | void = True 856 | ElseIf a = 0 And b = m Then 857 | full = True 858 | Else 859 | If a < 0 Then 860 | a = 0 861 | ElseIf a > m Then 862 | a = m 863 | End If 864 | If b < 0 Then 865 | b = 0 866 | ElseIf b > m Then 867 | b = m 868 | End If 869 | End If 870 | If IsArray(src) Then 871 | If void Then 872 | temp = Array() 873 | ElseIf full Then 874 | temp = src 875 | ElseIf a = 0 Then 876 | temp = src 877 | ReDim Preserve temp(b) 878 | Else 879 | ReDim temp(Abs(b - a)) 880 | Dim j 881 | j = 0 882 | d = IIf(a > b, -1, 1) 883 | For i = a To b Step d 884 | assign src(i), temp(j) 885 | j = j + 1 886 | Next 887 | End If 888 | If IsMissing(result) Then 889 | src = temp 890 | Else 891 | result = temp 892 | End If 893 | ElseIf TypeOf src Is Dictionary Then 894 | If void Then 895 | Set temp = New Dictionary 896 | temp.CompareMode = src.CompareMode 897 | ElseIf full Then 898 | Set temp = jsonExt.cloneDictionary(src) 899 | Else 900 | Set temp = New Dictionary 901 | temp.CompareMode = src.CompareMode 902 | Dim keys 903 | keys = src.keys() 904 | d = IIf(a > b, -1, 1) 905 | For i = a To b Step d 906 | If IsObject(src(keys(i))) Then 907 | Set temp(keys(i)) = src(keys(i)) 908 | Else 909 | temp(keys(i)) = src(keys(i)) 910 | End If 911 | Next 912 | End If 913 | If IsMissing(result) Then 914 | Set src = temp 915 | Else 916 | Set result = temp 917 | End If 918 | Else 919 | assign src, result 920 | End If 921 | 922 | End Sub 923 | 924 | Public Sub getAvg(root, path, avg, sum, qty) 925 | 926 | ' compute sum and average of root array or object values by relative path 927 | ' input: 928 | ' root - source array or object of entities to be processed 929 | ' path - string, expression in JS format, path relative to root array or object, or array of path components 930 | ' output: 931 | ' path - array of path components 932 | ' avg - avg value 933 | ' sum - sum of values 934 | ' qty - amount of processed entities 935 | 936 | Dim k 937 | Dim entry 938 | Dim exists 939 | sum = 0 940 | qty = 0 941 | If IsArray(root) Then 942 | For k = 0 To safeUBound(root) 943 | selectElement root(k), path, entry, exists 944 | If exists Then 945 | If IsNumeric(entry) Then 946 | qty = qty + 1 947 | sum = sum + CDbl(entry) 948 | End If 949 | End If 950 | Next 951 | ElseIf TypeOf root Is Dictionary Then 952 | For Each k In root.keys() 953 | selectElement root(k), path, entry, exists 954 | If exists Then 955 | If IsNumeric(entry) Then 956 | qty = qty + 1 957 | sum = sum + CDbl(entry) 958 | End If 959 | End If 960 | Next 961 | End If 962 | If qty > 0 Then 963 | avg = sum / qty 964 | End If 965 | 966 | End Sub 967 | 968 | Public Sub getMax(root, path, key, ret, qty) 969 | 970 | ' retrieve entity from root array or object having max value by relative path 971 | ' input: 972 | ' root - source array or object entity to be retrieved from 973 | ' path - string, expression in JS format, path relative to root array or object, or array of path components 974 | ' output: 975 | ' path - array of path components 976 | ' key - max value entity key 977 | ' ret - max value 978 | ' qty - amount of processed entities 979 | 980 | Dim res 981 | res = Null 982 | Dim k 983 | Dim entry 984 | Dim exists 985 | Dim e 986 | qty = 0 987 | If IsArray(root) Then 988 | For k = 0 To safeUBound(root) 989 | selectElement root(k), path, entry, exists 990 | If exists Then 991 | If IsNumeric(entry) Then 992 | e = CDbl(entry) 993 | qty = qty + 1 994 | If res > e Then 995 | Else 996 | res = e 997 | key = k 998 | End If 999 | End If 1000 | End If 1001 | Next 1002 | ElseIf TypeOf root Is Dictionary Then 1003 | For Each k In root.keys() 1004 | selectElement root(k), path, entry, exists 1005 | If exists Then 1006 | If IsNumeric(entry) Then 1007 | e = CDbl(entry) 1008 | qty = qty + 1 1009 | If res > e Then 1010 | Else 1011 | res = e 1012 | key = k 1013 | End If 1014 | End If 1015 | End If 1016 | Next 1017 | End If 1018 | If qty > 0 Then 1019 | ret = res 1020 | End If 1021 | 1022 | End Sub 1023 | 1024 | Public Sub getMin(root, path, key, ret, qty) 1025 | 1026 | ' retrieve entity from root array or object having min value by relative path 1027 | ' input: 1028 | ' root - source array or object entity to be retrieved from 1029 | ' path - string, expression in JS format, path relative to root array or object, or array of path components 1030 | ' output: 1031 | ' path - array of path components 1032 | ' key - min value entity key 1033 | ' ret - min value 1034 | ' qty - amount of processed entities 1035 | 1036 | Dim res 1037 | res = Null 1038 | Dim k 1039 | Dim entry 1040 | Dim exists 1041 | Dim e 1042 | qty = 0 1043 | If IsArray(root) Then 1044 | For k = 0 To safeUBound(root) 1045 | selectElement root(k), path, entry, exists 1046 | If exists Then 1047 | If IsNumeric(entry) Then 1048 | e = CDbl(entry) 1049 | qty = qty + 1 1050 | If res < e Then 1051 | Else 1052 | res = e 1053 | key = k 1054 | End If 1055 | End If 1056 | End If 1057 | Next 1058 | ElseIf TypeOf root Is Dictionary Then 1059 | For Each k In root.keys() 1060 | selectElement root(k), path, entry, exists 1061 | If exists Then 1062 | If IsNumeric(entry) Then 1063 | e = CDbl(entry) 1064 | qty = qty + 1 1065 | If res < e Then 1066 | Else 1067 | res = e 1068 | key = k 1069 | End If 1070 | End If 1071 | End If 1072 | Next 1073 | End If 1074 | If qty > 0 Then 1075 | ret = res 1076 | End If 1077 | 1078 | End Sub 1079 | 1080 | Function safeUBound(a) 1081 | 1082 | safeUBound = -1 1083 | On Error Resume Next 1084 | safeUBound = UBound(a) 1085 | Err.Clear 1086 | 1087 | End Function 1088 | 1089 | Function isScalar(v) As Boolean 1090 | 1091 | Select Case VarType(v) 1092 | Case vbByte, vbCurrency, vbDate, vbDecimal, vbDouble, vbEmpty, vbInteger, vbLong, vbSingle, vbString 1093 | isScalar = True 1094 | Case Else 1095 | isScalar = False 1096 | End Select 1097 | 1098 | End Function 1099 | 1100 | Function cloneDictionary(srcDict) 1101 | 1102 | Dim destDict As Dictionary 1103 | Set destDict = New Dictionary 1104 | If TypeOf srcDict Is Dictionary Then 1105 | If Not srcDict Is Nothing Then 1106 | destDict.CompareMode = srcDict.CompareMode 1107 | Dim key 1108 | Dim temp 1109 | For Each key In srcDict.keys() 1110 | If IsObject(srcDict(key)) Then 1111 | 1112 | Set temp = srcDict(key) 1113 | Set destDict(key) = temp 1114 | Else 1115 | temp = srcDict(key) 1116 | destDict(key) = temp 1117 | End If 1118 | Next 1119 | End If 1120 | End If 1121 | Set cloneDictionary = destDict 1122 | 1123 | End Function 1124 | 1125 | Sub deepClone(srcElt, destElt) 1126 | 1127 | If IsArray(srcElt) Then 1128 | destElt = srcElt 1129 | If safeUBound(destElt) > -1 Then 1130 | Dim i 1131 | For i = 0 To UBound(destElt) 1132 | Dim tmp 1133 | deepClone destElt(i), tmp 1134 | If IsObject(tmp) Then 1135 | Set destElt(i) = tmp 1136 | Else 1137 | destElt(i) = tmp 1138 | End If 1139 | Next 1140 | End If 1141 | ElseIf IsObject(srcElt) Then 1142 | If TypeOf srcElt Is Dictionary Then 1143 | Set destElt = New Dictionary 1144 | destElt.CompareMode = srcElt.CompareMode 1145 | Dim key 1146 | For Each key In srcElt 1147 | deepClone srcElt(key), tmp 1148 | If IsObject(tmp) Then 1149 | Set destElt(key) = tmp 1150 | Else 1151 | destElt(key) = tmp 1152 | End If 1153 | Next 1154 | Else 1155 | Set destElt = srcElt 1156 | End If 1157 | Else 1158 | destElt = srcElt 1159 | End If 1160 | 1161 | End Sub 1162 | 1163 | Sub pushItem( _ 1164 | destArray, _ 1165 | sourceElement, _ 1166 | Optional optionAppend As Boolean = True, _ 1167 | Optional optionNestArrays As Boolean = True _ 1168 | ) 1169 | 1170 | ' not optionAppend => create array 1171 | ' sourceElement array and optionAppend => do not create array 1172 | ' sourceElement not array and optionAppend => create array with single elt 1173 | Select Case True 1174 | Case Not optionAppend Or IsEmpty(destArray) 1175 | destArray = Array() 1176 | Case Not IsArray(destArray) 1177 | destArray = Array(destArray) 1178 | End Select 1179 | If IsArray(sourceElement) And Not optionNestArrays Then 1180 | Dim n As Long 1181 | Dim j As Long 1182 | Dim i As Long 1183 | n = UBound(destArray) 1184 | ReDim Preserve destArray(LBound(destArray) To n + UBound(sourceElement) - LBound(sourceElement) + 1) 1185 | j = 1 1186 | For i = LBound(sourceElement) To UBound(sourceElement) 1187 | assign sourceElement(i), destArray(n + j) 1188 | j = j + 1 1189 | Next 1190 | Else 1191 | ReDim Preserve destArray(LBound(destArray) To UBound(destArray) + 1) 1192 | assign sourceElement, destArray(UBound(destArray)) 1193 | End If 1194 | 1195 | End Sub 1196 | 1197 | Sub assign(source, dest) 1198 | 1199 | If IsObject(source) Then 1200 | Set dest = source 1201 | Else 1202 | dest = source 1203 | End If 1204 | 1205 | End Sub 1206 | -------------------------------------------------------------------------------- /Beta/simpleJsonJSParser.bas: -------------------------------------------------------------------------------- 1 | Attribute VB_Name = "simpleJsonJSParser" 2 | 3 | ' Douglas Crockford json2.js implementation for VBA 4 | ' version 2022-09-29 5 | ' https://github.com/douglascrockford/JSON-js/blob/master/json2.js 6 | ' 7 | ' simpleJsonJSParser derived from jsJsonParser (beta) v0.1.2 8 | ' Copyright (C) 2021 omegastripes 9 | ' omegastripes@yandex.ru 10 | ' https://github.com/omegastripes/VBA-JSON-parser 11 | ' 12 | ' This program is free software: you can redistribute it and/or modify 13 | ' it under the terms of the GNU General Public License as published by 14 | ' the Free Software Foundation, either version 3 of the License, or 15 | ' (at your option) any later version. 16 | ' 17 | ' This program is distributed in the hope that it will be useful, 18 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | ' GNU General Public License for more details. 21 | ' 22 | ' You should have received a copy of the GNU General Public License 23 | ' along with this program. If not, see . 24 | 25 | Option Explicit 26 | 27 | Sub test() 28 | Dim sample 29 | sample = "[{""a"":55}, 100]" 30 | Dim result 31 | Dim js 32 | Dim ok 33 | assign parseToVb(sample, js, , ok), result 34 | Debug.Print jsonParser.stringify(js, "", vbTab) 35 | Stop 36 | End Sub 37 | 38 | Function jsonParser() 39 | Static document As Object 40 | Static json As Object 41 | If json Is Nothing Then 42 | Set document = CreateObject("htmlfile") 43 | document.Write "'" 44 | document.parentWindow.execScript Replace( _ 45 | "`object`!=typeof JSON&&(JSON={}),function(){`use strict`;function f(t){return 10>t?`0`+t:t}function this_value(){return this.valueOf()}function quote(t){return rx_escapable.lastIndex=" & _ 46 | "0,rx_escapable.test(t)?'`'+t.replace(rx_escapable,function(t){var e=meta[t];return`string`==typeof e?e:`\\u`+(`0000`+t.charCodeAt(0).toString(16)).slice(-4)})+'`':'`'+t+'`'}function str(t,e){var r,n,o,u,f,a=gap,i=e[t];switch(i&&`object`==typeof i&&`f" & _ 47 | "unction`==typeof i.toJSON&&(i=i.toJSON(t)),`function`==typeof rep&&(i=rep.call(e,t,i)),typeof i){case`string`:return quote(i);case`number`:return isFinite(i)?String(i):`null`;case`boolean`:case`null`:return String(i);case`object`:if(!i)return`null`;i" & _ 48 | "f(gap+=indent,f=[],`[object Array]`===Object.prototype.toString.apply(i)){for(u=i.length,r=0;u>r;r+=1)f[r]=str(r,i)||`null`;return o=0===f.length?`[]`:gap?`[\n`+gap+f.join(`,\n`+gap)+`\n`+a+`]`:`[`+f.join(`,`)+`]`,gap=a,o}if(rep&&`object`==typeof rep" & _ 49 | ")for(u=rep.length,r=0;u>r;r+=1)`string`==typeof rep[r]&&(n=rep[r],o=str(n,i),o&&f.push(quote(n)+(gap?`: `:`:`)+o));else for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(o=str(n,i),o&&f.push(quote(n)+(gap?`: `:`:`)+o));return o=0===f.length?`{}`" & _ 50 | ":gap?`{\n`+gap+f.join(`,\n`+gap)+`\n`+a+`}`:`{`+f.join(`,`)+`}`,gap=a,o}}var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:[`\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/`[^`\\\n\r]*`|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/" & _ 51 | "g,rx_escapable=/[\\`\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\u" & _ 52 | "fff0-\uffff]/g;`function`!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+`-`+f(this.getUTCMonth()+1)+`-`+f(this.getUTCDate())+`T`+f(this.getUTCHours())+`:`+f(this.getUTCMinutes()" & _ 53 | ")+`:`+f(this.getUTCSeconds())+`Z`:null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value);var gap,indent,meta,rep;`function`!=typeof JSON.stringify&&(meta={`\b`:`\\b`,` `:`\\t`,`\n`:`\\n`,`\f`:" & _ 54 | "`\\f`,`\r`:`\\r`,'`':'\\`',`\\`:`\\\\`},JSON.stringify=function(t,e,r){var n;if(gap=``,indent=``,`number`==typeof r)for(n=0;r>n;n+=1)indent+=` `;else`string`==typeof r&&(indent=r);if(rep=e,e&&`function`!=typeof e&&(`object`!=typeof e||`number`!=typeo" & _ 55 | "f e.length))throw new Error(`JSON.stringify`);return str(``,{``:t})}),`function`!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(t,e){var r,n,o=t[e];if(o&&`object`==typeof o)for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(" & _ 56 | "n=walk(o,r),void 0!==n?o[r]=n:delete o[r]);return reviver.call(t,e,o)}var j;if(text=String(text),rx_dangerous.lastIndex=0,rx_dangerous.test(text)&&(text=text.replace(rx_dangerous,function(t){return`\\u`+(`0000`+t.charCodeAt(0).toString(16)).slice(-4)" & _ 57 | "})),rx_one.test(text.replace(rx_two,`@`).replace(rx_three,`]`).replace(rx_four,``)))return j=eval(`(`+text+`)`),`function`==typeof reviver?walk({``:j},``):j;throw new SyntaxError(`JSON.parse`)})}();var json=JSON;json.GetType=json.getType=function(t){" & _ 58 | "switch(typeof t){case`string`:case`number`:case`boolean`:case`null`:return typeof t;case`object`:if(!t)return`null`;if(`[object Array]`===Object.prototype.toString.apply(t))return`array`}return`object`};json.CloneDict=json.cloneDict=function(t,e){for" & _ 59 | "(var r in t)e.Add(r,t[r]);return e};json.Parse=json.parse;json.Stringify=json.stringify;", _ 60 | "`", """" _ 61 | ) 62 | Set json = document.parentWindow.json 63 | End If 64 | Set jsonParser = json 65 | End Function 66 | 67 | Public Function parseToVb(sample, Optional jsonData, Optional result, Optional success) 68 | result = Empty 69 | success = False 70 | On Error Resume Next 71 | Set jsonData = jsonParser.parse(sample) 72 | If jsonData Is Nothing Then Exit Function 73 | Dim vbaJsonObject 74 | repack jsonData, result 75 | If Err.Number <> 0 Then Exit Function 76 | parseToVb = 1 77 | assign result, parseToVb 78 | success = True 79 | End Function 80 | 81 | Private Sub repack(source, result) 82 | Select Case jsonParser.getType(source) 83 | Case "array" 84 | result = jsonParser.cloneDict(source, CreateObject("Scripting.Dictionary")).items 85 | Dim i 86 | For i = 0 To UBound(result) 87 | Dim ret 88 | repack result(i), ret 89 | If IsObject(ret) Then 90 | Set result(i) = ret 91 | Else 92 | result(i) = ret 93 | End If 94 | Next 95 | Case "object" 96 | Set result = jsonParser.cloneDict(source, CreateObject("Scripting.Dictionary")) 97 | For Each i In result 98 | repack result(i), ret 99 | If IsObject(ret) Then 100 | Set result(i) = ret 101 | Else 102 | result(i) = ret 103 | End If 104 | Next 105 | Case "string" 106 | result = CStr(source) 107 | Case "number" 108 | result = CDbl(source) 109 | Case "boolean" 110 | result = CBool(source) 111 | Case "null" 112 | result = Null 113 | End Select 114 | End Sub 115 | 116 | Sub assign(src, dest) 117 | If IsObject(src) Then 118 | Set dest = src 119 | Else 120 | dest = src 121 | End If 122 | End Sub 123 | 124 | 125 | -------------------------------------------------------------------------------- /JSON.bas: -------------------------------------------------------------------------------- 1 | Attribute VB_Name = "JSON" 2 | ' VBA JSON parser, Backus-Naur form JSON parser based on RegEx v1.7.22 3 | ' Copyright (C) 2015-2024 omegastripes 4 | ' omegastripes@yandex.ru 5 | ' https://github.com/omegastripes/VBA-JSON-parser 6 | ' 7 | ' This program is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' This program is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with this program. If not, see . 19 | 20 | Option Explicit 21 | 22 | ' Need to include a reference to "Microsoft Scripting Runtime". 23 | 24 | Private sBuffer As String 25 | Private oTokens As Dictionary 26 | Private oRegEx As Object 27 | Private bMatch As Boolean 28 | Private oChunks As Dictionary 29 | Private oHeader As Dictionary 30 | Private aData() As Variant 31 | Private i As Long 32 | Private sDelim As String 33 | Private sTabChar As String 34 | Private sLfChar As String 35 | Private sSpcChar As String 36 | 37 | Sub Parse(ByVal sSample As String, vJSON As Variant, sState As String) 38 | 39 | ' Input: 40 | ' sSample - source JSON string 41 | ' Output: 42 | ' vJson - created object or array to be returned as result 43 | ' sState - string Object|Array|Error depending on result 44 | 45 | sBuffer = sSample 46 | Set oTokens = New Dictionary 47 | Set oRegEx = CreateObject("VBScript.RegExp") 48 | With oRegEx ' Patterns based on specification http://www.json.org/ 49 | .Global = True 50 | .MultiLine = True 51 | .IgnoreCase = True ' Unspecified True, False, Null accepted 52 | .Pattern = "(?:'[^']*'|""(?:\\""|[^""])*"")(?=\s*[,\:\]\}])" ' Double-quoted string, unspecified quoted string 53 | Tokenize "s" 54 | .Pattern = "[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:e[+-]?\d+)?(?=\s*[,\]\}])" ' Number, E notation number 55 | Tokenize "d" 56 | .Pattern = "\b(?:true|false|null)(?=\s*[,\]\}])" ' Constants true, false, null 57 | Tokenize "c" 58 | .Pattern = "\b[A-Za-z_]\w*(?=\s*\:)" ' Unspecified non-double-quoted property name accepted 59 | Tokenize "n" 60 | .Pattern = "\s+" 61 | sBuffer = .Replace(sBuffer, "") ' Remove unnecessary spaces 62 | .MultiLine = False 63 | Do 64 | bMatch = False 65 | .Pattern = "<\d+(?:[sn])>\:<\d+[codas]>" ' Object property structure 66 | Tokenize "p" 67 | .Pattern = "\{(?:<\d+p>(?:,<\d+p>)*)?,?\}" ' Object structure 68 | Tokenize "o" 69 | .Pattern = "\[(?:<\d+[codas]>(?:,<\d+[codas]>)*)?,?\]" ' Array structure 70 | Tokenize "a" 71 | Loop While bMatch 72 | .Pattern = "^<\d+[oa]>$" ' Top level object structure, unspecified array accepted 73 | If .Test(sBuffer) And oTokens.Exists(sBuffer) Then 74 | sDelim = Left(Right(1 / 2, 2), 1) 75 | Retrieve sBuffer, vJSON 76 | sState = IIf(IsObject(vJSON), "Object", "Array") 77 | Else 78 | vJSON = Null 79 | sState = "Error" 80 | End If 81 | End With 82 | Set oTokens = Nothing 83 | Set oRegEx = Nothing 84 | 85 | End Sub 86 | 87 | Private Sub Tokenize(sType) 88 | 89 | Dim aContent() As String 90 | Dim lCopyIndex As Long 91 | Dim i As Long 92 | Dim sKey As String 93 | 94 | With oRegEx.Execute(sBuffer) 95 | If .Count = 0 Then Exit Sub 96 | ReDim aContent(0 To .Count - 1) 97 | lCopyIndex = 1 98 | For i = 0 To .Count - 1 99 | With .Item(i) 100 | sKey = "<" & oTokens.Count & sType & ">" 101 | oTokens(sKey) = .Value 102 | aContent(i) = Mid(sBuffer, lCopyIndex, .FirstIndex - lCopyIndex + 1) & sKey 103 | lCopyIndex = .FirstIndex + .Length + 1 104 | End With 105 | Next 106 | End With 107 | sBuffer = Join(aContent, "") & Mid(sBuffer, lCopyIndex, Len(sBuffer) - lCopyIndex + 1) 108 | bMatch = True 109 | 110 | End Sub 111 | 112 | Private Sub Retrieve(sTokenKey, vTransfer) 113 | 114 | Dim sTokenValue As String 115 | Dim sName As Variant 116 | Dim vValue As Variant 117 | Dim aTokens() As String 118 | Dim i As Long 119 | 120 | sTokenValue = oTokens(sTokenKey) 121 | With oRegEx 122 | .Global = True 123 | Select Case Left(Right(sTokenKey, 2), 1) 124 | Case "o" 125 | Set vTransfer = New Dictionary 126 | aTokens = Split(sTokenValue, "<") 127 | For i = 1 To UBound(aTokens) 128 | Retrieve "<" & Split(aTokens(i), ">", 2)(0) & ">", vTransfer 129 | Next 130 | Case "p" 131 | aTokens = Split(sTokenValue, "<", 4) 132 | Retrieve "<" & Split(aTokens(1), ">", 2)(0) & ">", sName 133 | Retrieve "<" & Split(aTokens(2), ">", 2)(0) & ">", vValue 134 | If IsObject(vValue) Then 135 | Set vTransfer(sName) = vValue 136 | Else 137 | vTransfer(sName) = vValue 138 | End If 139 | Case "a" 140 | aTokens = Split(sTokenValue, "<") 141 | If UBound(aTokens) = 0 Then 142 | vTransfer = Array() 143 | Else 144 | ReDim vTransfer(0 To UBound(aTokens) - 1) 145 | For i = 1 To UBound(aTokens) 146 | Retrieve "<" & Split(aTokens(i), ">", 2)(0) & ">", vValue 147 | If IsObject(vValue) Then 148 | Set vTransfer(i - 1) = vValue 149 | Else 150 | vTransfer(i - 1) = vValue 151 | End If 152 | Next 153 | End If 154 | Case "n" 155 | vTransfer = sTokenValue 156 | Case "s" 157 | vTransfer = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _ 158 | Mid(sTokenValue, 2, Len(sTokenValue) - 2), _ 159 | "\""", """"), _ 160 | "\\", "\" & vbNullChar), _ 161 | "\/", "/"), _ 162 | "\b", Chr(8)), _ 163 | "\f", Chr(12)), _ 164 | "\n", vbLf), _ 165 | "\r", vbCr), _ 166 | "\t", vbTab) 167 | .Global = False 168 | .Pattern = "\\u[0-9a-fA-F]{4}" 169 | Do While .Test(vTransfer) 170 | vTransfer = .Replace(vTransfer, ChrW(("&H" & Right(.Execute(vTransfer)(0).Value, 4)) * 1)) 171 | Loop 172 | vTransfer = Replace(vTransfer, "\" & vbNullChar, "\") 173 | Case "d" 174 | vTransfer = CDbl(Replace(sTokenValue, ".", sDelim)) 175 | Case "c" 176 | Select Case LCase(sTokenValue) 177 | Case "true" 178 | vTransfer = True 179 | Case "false" 180 | vTransfer = False 181 | Case "null" 182 | vTransfer = Null 183 | End Select 184 | End Select 185 | End With 186 | 187 | End Sub 188 | 189 | Function Serialize(vJSON As Variant, Optional sTab As String = vbTab) As String 190 | 191 | If sTab = "" Then 192 | sTabChar = "" 193 | sLfChar = "" 194 | sSpcChar = "" 195 | Else 196 | sTabChar = sTab 197 | sLfChar = vbCrLf 198 | sSpcChar = " " 199 | End If 200 | Set oChunks = New Dictionary 201 | SerializeElement vJSON, "" 202 | Serialize = Join(oChunks.Items(), "") 203 | Set oChunks = Nothing 204 | 205 | End Function 206 | 207 | Private Sub SerializeElement(vElement As Variant, ByVal sIndent As String) 208 | 209 | Dim aKeys() As Variant 210 | Dim i As Long 211 | 212 | With oChunks 213 | Select Case VarType(vElement) 214 | Case vbObject 215 | If Not TypeOf vElement Is Dictionary Then 216 | .Item(.Count) = "{}" 217 | ElseIf vElement.Count = 0 Then 218 | .Item(.Count) = "{}" 219 | Else 220 | .Item(.Count) = "{" & sLfChar 221 | aKeys = vElement.Keys 222 | For i = 0 To UBound(aKeys) 223 | .Item(.Count) = sIndent & sTabChar & """" & EscapeJsonString(aKeys(i)) & """" & ":" & sSpcChar 224 | SerializeElement vElement(aKeys(i)), sIndent & sTabChar 225 | If Not (i = UBound(aKeys)) Then .Item(.Count) = "," 226 | .Item(.Count) = sLfChar 227 | Next 228 | .Item(.Count) = sIndent & "}" 229 | End If 230 | Case Is >= vbArray 231 | If UBound(vElement) = -1 Then 232 | .Item(.Count) = "[]" 233 | Else 234 | .Item(.Count) = "[" & sLfChar 235 | For i = 0 To UBound(vElement) 236 | .Item(.Count) = sIndent & sTabChar 237 | SerializeElement vElement(i), sIndent & sTabChar 238 | If Not (i = UBound(vElement)) Then .Item(.Count) = "," 'sResult = sResult & "," 239 | .Item(.Count) = sLfChar 240 | Next 241 | .Item(.Count) = sIndent & "]" 242 | End If 243 | Case vbInteger, vbLong 244 | .Item(.Count) = vElement 245 | Case vbSingle, vbDouble 246 | .Item(.Count) = Replace(vElement, ",", ".") 247 | Case vbNull, vbError 248 | .Item(.Count) = "null" 249 | Case vbBoolean 250 | .Item(.Count) = IIf(vElement, "true", "false") 251 | Case Else 252 | .Item(.Count) = """" & EscapeJsonString(vElement) & """" 253 | End Select 254 | End With 255 | 256 | End Sub 257 | 258 | Private Function EscapeJsonString(s) 259 | 260 | EscapeJsonString = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(s, _ 261 | "\", "\\"), _ 262 | """", "\"""), _ 263 | "/", "\/"), _ 264 | Chr(8), "\b"), _ 265 | Chr(12), "\f"), _ 266 | vbLf, "\n"), _ 267 | vbCr, "\r"), _ 268 | vbTab, "\t") 269 | 270 | End Function 271 | 272 | Function ToYaml(vJSON As Variant) As String 273 | 274 | Select Case VarType(vJSON) 275 | Case vbObject, Is >= vbArray 276 | Set oChunks = New Dictionary 277 | ToYamlElement vJSON, "" 278 | oChunks.Remove 0 279 | ToYaml = Join(oChunks.Items(), "") 280 | Set oChunks = Nothing 281 | Case vbNull, vbError 282 | ToYaml = "Null" 283 | Case vbBoolean 284 | ToYaml = IIf(vJSON, "True", "False") 285 | Case Else 286 | ToYaml = CStr(vJSON) 287 | End Select 288 | 289 | End Function 290 | 291 | Private Sub ToYamlElement(vElement As Variant, ByVal sIndent As String) 292 | 293 | Dim aKeys() As Variant 294 | Dim i As Long 295 | 296 | With oChunks 297 | Select Case VarType(vElement) 298 | Case vbObject 299 | If Not TypeOf vElement Is Dictionary Then 300 | .Item(.Count) = "''" 301 | ElseIf vElement.Count = 0 Then 302 | .Item(.Count) = "''" 303 | Else 304 | .Item(.Count) = vbCrLf 305 | aKeys = vElement.Keys 306 | For i = 0 To UBound(aKeys) 307 | .Item(.Count) = sIndent & aKeys(i) & ": " 308 | ToYamlElement vElement(aKeys(i)), sIndent & " " 309 | If Not (i = UBound(aKeys)) Then .Item(.Count) = vbCrLf 310 | Next 311 | End If 312 | Case Is >= vbArray 313 | If UBound(vElement) = -1 Then 314 | .Item(.Count) = "''" 315 | Else 316 | .Item(.Count) = vbCrLf 317 | For i = 0 To UBound(vElement) 318 | .Item(.Count) = sIndent & i & ": " 319 | ToYamlElement vElement(i), sIndent & " " 320 | If Not (i = UBound(vElement)) Then .Item(.Count) = vbCrLf 321 | Next 322 | End If 323 | Case vbNull, vbError 324 | .Item(.Count) = "Null" 325 | Case vbBoolean 326 | .Item(.Count) = IIf(vElement, "True", "False") 327 | Case Else 328 | .Item(.Count) = CStr(vElement) 329 | End Select 330 | End With 331 | 332 | End Sub 333 | 334 | Sub ToArray(vJSON As Variant, aRows() As Variant, aHeader() As Variant) 335 | 336 | ' Input: 337 | ' vJSON - Array or Object which contains rows data 338 | ' Output: 339 | ' aRows - 2d array representing JSON data 340 | ' aHeader - 1d array of property names 341 | 342 | Dim sName As Variant 343 | 344 | Set oHeader = New Dictionary 345 | Select Case VarType(vJSON) 346 | Case vbObject 347 | If vJSON.Count > 0 Then 348 | ReDim aData(0 To vJSON.Count - 1, 0 To 0) 349 | oHeader("#") = 0 350 | i = 0 351 | For Each sName In vJSON.Keys 352 | aData(i, 0) = sName 353 | ToArrayElement vJSON(sName), "" 354 | i = i + 1 355 | Next 356 | Else 357 | ReDim aData(0 To 0, 0 To 0) 358 | End If 359 | Case Is >= vbArray 360 | If UBound(vJSON) >= 0 Then 361 | ReDim aData(0 To UBound(vJSON), 0 To 0) 362 | For i = 0 To UBound(vJSON) 363 | ToArrayElement vJSON(i), "" 364 | Next 365 | Else 366 | ReDim aData(0 To 0, 0 To 0) 367 | End If 368 | Case Else 369 | ReDim aData(0 To 0, 0 To 0) 370 | aData(0, 0) = vJSON 371 | End Select 372 | aHeader = oHeader.Keys() 373 | Set oHeader = Nothing 374 | aRows = aData 375 | Erase aData 376 | 377 | End Sub 378 | 379 | Private Sub ToArrayElement(vElement As Variant, sFieldName As String) 380 | 381 | Dim sName As Variant 382 | Dim j As Long 383 | 384 | Select Case VarType(vElement) 385 | Case vbObject ' Collection of objects 386 | For Each sName In vElement.Keys 387 | ToArrayElement vElement(sName), sFieldName & IIf(sFieldName = "", "", ".") & sName 388 | Next 389 | Case Is >= vbArray ' Collection of arrays 390 | For j = 0 To UBound(vElement) 391 | ToArrayElement vElement(j), sFieldName & "[" & j & "]" 392 | Next 393 | Case Else 394 | If Not oHeader.Exists(sFieldName) Then 395 | oHeader(sFieldName) = oHeader.Count 396 | If UBound(aData, 2) < oHeader.Count - 1 Then ReDim Preserve aData(0 To UBound(aData, 1), 0 To oHeader.Count - 1) 397 | End If 398 | j = oHeader(sFieldName) 399 | aData(i, j) = vElement 400 | End Select 401 | 402 | End Sub 403 | 404 | Sub Flatten(vJSON As Variant, vResult As Variant) 405 | 406 | ' Input: 407 | ' vJSON - Array or Object which contains JSON data 408 | ' Output: 409 | ' oResult - Flatten JSON data object 410 | 411 | Set oChunks = New Dictionary 412 | FlattenElement vJSON, "" 413 | Set vResult = oChunks 414 | Set oChunks = Nothing 415 | 416 | End Sub 417 | 418 | Private Sub FlattenElement(vElement As Variant, sProperty As String) 419 | 420 | Dim vKey 421 | Dim i As Long 422 | 423 | Select Case True 424 | Case TypeOf vElement Is Dictionary 425 | If vElement.Count > 0 Then 426 | For Each vKey In vElement.Keys 427 | FlattenElement vElement(vKey), IIf(sProperty <> "", sProperty & "." & vKey, vKey) 428 | Next 429 | End If 430 | Case IsObject(vElement) 431 | Case IsArray(vElement) 432 | For i = 0 To UBound(vElement) 433 | FlattenElement vElement(i), sProperty & "[" & i & "]" 434 | Next 435 | Case Else 436 | oChunks(sProperty) = vElement 437 | End Select 438 | 439 | End Sub 440 | 441 | Sub Unflatten(oFlatten, vJSON, bSuccess) 442 | 443 | ' Input: 444 | ' oFlatten - source dictionary containing JSON data 445 | ' Output: 446 | ' vJSON - created object or array to be returned as result 447 | ' bSuccess - boolean indicating successful completion 448 | 449 | Dim sPath 450 | Dim vValue 451 | Dim aQualifiers 452 | Dim lNextLevel 453 | 454 | bSuccess = TypeOf oFlatten Is Dictionary 455 | If Not bSuccess Then Exit Sub 456 | For Each sPath In oFlatten.Keys 457 | If IsObject(oFlatten(sPath)) Then 458 | Set vValue = oFlatten(sPath) 459 | Else 460 | vValue = oFlatten(sPath) 461 | End If 462 | If Left(sPath, 1) <> "[" And Left(sPath, 1) <> "." Then 463 | sPath = "." & sPath 464 | End If 465 | aQualifiers = Split(Replace(Replace(sPath, ".", vbNullChar), "[", vbNullChar), vbNullChar) 466 | lNextLevel = 1 467 | UnflattenElement vJSON, lNextLevel, aQualifiers, vValue, bSuccess 468 | If Not bSuccess Then Exit Sub 469 | Next 470 | 471 | End Sub 472 | 473 | Private Sub UnflattenElement(vParent, lNextLevel, aQualifiers, vValue, bSuccess) 474 | 475 | Dim vNextQualifier 476 | Dim sNum 477 | Dim vChild 478 | 479 | bSuccess = False 480 | If lNextLevel > UBound(aQualifiers) Then 481 | If IsObject(vValue) Then 482 | Set vParent = vValue 483 | Else 484 | vParent = vValue 485 | End If 486 | bSuccess = True 487 | Exit Sub 488 | End If 489 | vNextQualifier = aQualifiers(lNextLevel) 490 | If Right(vNextQualifier, 1) = "]" Then 491 | sNum = Left(vNextQualifier, Len(vNextQualifier) - 1) 492 | If IsNumeric(sNum) Then 493 | vNextQualifier = CLng(sNum) 494 | End If 495 | End If 496 | If VarType(vNextQualifier) = vbLong Then 497 | If VarType(vParent) = vbEmpty Then 498 | vParent = Array() 499 | ElseIf Not IsArray(vParent) Then 500 | Exit Sub 501 | End If 502 | If UBound(vParent) < vNextQualifier Then 503 | ReDim Preserve vParent(vNextQualifier) 504 | End If 505 | Else 506 | If VarType(vParent) = vbEmpty Then 507 | Set vParent = New Dictionary 508 | ElseIf Not IsObject(vParent) Then 509 | Exit Sub 510 | ElseIf Not TypeOf vParent Is Dictionary Then 511 | Exit Sub 512 | End If 513 | End If 514 | If IsObject(vParent(vNextQualifier)) Then 515 | Set vChild = vParent(vNextQualifier) 516 | Else 517 | vChild = vParent(vNextQualifier) 518 | End If 519 | UnflattenElement vChild, lNextLevel + 1, aQualifiers, vValue, bSuccess 520 | If Not bSuccess Then 521 | Exit Sub 522 | End If 523 | If IsObject(vChild) Then 524 | Set vParent(vNextQualifier) = vChild 525 | Else 526 | vParent(vNextQualifier) = vChild 527 | End If 528 | bSuccess = True 529 | 530 | End Sub 531 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [

](https://github.com/omegastripes/VBA-JSON-parser/releases) 2 | # VBA JSON Parser 3 | [![release](https://img.shields.io/github/release/omegastripes/VBA-JSON-parser.svg?style=flat&logo=github)](https://github.com/omegastripes/VBA-JSON-parser/releases/latest) [![last-commit](https://img.shields.io/github/last-commit/omegastripes/VBA-JSON-parser.svg?style=flat)](https://github.com/omegastripes/VBA-JSON-parser/commits/master) [![downloads](https://img.shields.io/github/downloads/omegastripes/VBA-JSON-parser/total.svg?style=flat)](https://somsubhra.github.io/github-release-stats/?username=omegastripes&repository=VBA-JSON-parser&page=1) [![code-size](https://img.shields.io/github/languages/code-size/omegastripes/VBA-JSON-parser.svg?style=flat)](https://github.com/omegastripes/VBA-JSON-parser) [![language](https://img.shields.io/github/languages/top/omegastripes/VBA-JSON-parser.svg?style=flat)](https://github.com/omegastripes/VBA-JSON-parser/search?l=vba) [![license](https://img.shields.io/github/license/omegastripes/VBA-JSON-parser.svg?style=flat)](https://github.com/omegastripes/VBA-JSON-parser/blob/master/LICENSE) [![gitter](https://img.shields.io/gitter/room/omegastripes/VBA-JSON-parser.svg?style=flat&logo=gitter)](https://gitter.im/omegastripes) [![tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Easy%20and%20flexible%20JSON%20processing%20for%20VBA%F0%9F%92%A5&url=https://github.com/omegastripes/VBA-JSON-parser&via=omegastripes&hashtags=vba,json,parse,excel) 4 | 5 | [Backus-Naur Form](https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form) JSON Parser based on RegEx for VBA. 6 | ## Purpose and Features 7 | - Parsing JSON string to a structure of nested Dictionaries and Arrays. JSON Objects `{}` are represented by Dictionaries, providing `.Count`, `.Exists()`, `.Item()`, `.Items`, `.Keys` properties and methods. JSON Arrays `[]` are the conventional zero-based VB Arrays, so `UBound() + 1` allows to get the number of elements. Such approach makes easy and straightforward access to structure elements (parsing result is returned via variable passed by ref to sub, so that both an array and a dictionary object can be returned). 8 | - Serializing JSON structure with beautification. 9 | - Building 2D Array based on table-like JSON structure. 10 | - Flattening and unflattening JSON structure. 11 | - Serializing JSON structure into [YAML format](https://yaml.org/) string. 12 | - Parser complies with [JSON Standard](http://json.org/). 13 | - Allows few non-stantard features in JSON string parsing: single quoted and unquoted object keys, single quoted strings, capitalised `True`, `False` and `Null` constants, and trailing commas. 14 | - Invulnerable for malicious JS code injections. 15 | ## Compatibility 16 | Supported by MS Windows Office 2003+ (Excel, Word, Access, PowerPoint, Publisher, Visio etc.), CorelDraw, AutoCAD and many others applications with hosted VBA. And even VB6. 17 | ## Deployment 18 | Start from example project, Excel workbook is available for downloading in the [latest release](https://github.com/omegastripes/VBA-JSON-parser/releases/latest). 19 | 20 | Or 21 | 22 | Import **JSON.bas** module into the VBA Project for JSON processing. Need to include a reference to **Microsoft Scripting Runtime**. 23 |
How to import? 24 |

25 | 26 | Download and save JSON.bas to a file - open [the page with JSON.bas code](https://github.com/omegastripes/VBA-JSON-parser/blob/master/JSON.bas), right-click on Raw button, choose Save link as... (for Chrome): 27 | 28 | ![download](https://user-images.githubusercontent.com/3822668/52233449-33dde700-28d0-11e9-97b9-f61fd98c16fd.png) 29 | 30 | Import JSON.bas into the VBA Project - open Visual Basic Editor by pressing Alt+F11, right-click on Project Tree, choose Import File, select downloaded JSON.bas: 31 | 32 | ![import](https://user-images.githubusercontent.com/3822668/52232296-31c65900-28cd-11e9-8164-94ca71c06595.png) 33 | 34 | Or you may drag'n'drop downloaded JSON.bas from explorer window (or desktop) directly into the VBA Project Tree. 35 | 36 |

37 |
38 |
How to add reference? 39 |

40 | 41 | Open Visual Basic Editor by pressing Alt+F11, click Menu - Tools - References, scroll down to **Microsoft Scripting Runtime** and check it, press OK: 42 | 43 | ![add reference](https://user-images.githubusercontent.com/3822668/71650262-ca579a00-2d25-11ea-9701-4c21dc280ad7.png) 44 | 45 | ### ![attention](https://user-images.githubusercontent.com/3822668/76687641-cd7cd980-6636-11ea-808d-7fd088be307b.png) MS Word Object Library compatibility note 46 | When referencing both **Microsoft Scripting Runtime** and **Microsoft Word Object Library** make sure that **Microsoft Scripting Runtime** located above **Microsoft Word Object Library** in the the list, if not so then ajust the position by clicking Priority arrows to the right of the list. 47 | 48 | ![Microsoft Scripting Runtime and Microsoft Word Object Library](https://user-images.githubusercontent.com/3822668/76686982-ed110380-6630-11ea-8d6e-3b4cab94b219.png) 49 | 50 | Otherwise you have to change all `Dictionary` references to `Scripting.Dictionary` in your VBA code. 51 | 52 |

53 |
54 | 55 | ## Usage 56 | Here is simple example for MS Excel, put the below code into standard module: 57 | 58 | ```vba 59 | Option Explicit 60 | 61 | Sub Test() 62 | 63 | Dim sJSONString As String 64 | Dim vJSON 65 | Dim sState As String 66 | Dim vFlat 67 | 68 | ' Retrieve JSON response 69 | With CreateObject("MSXML2.XMLHTTP") 70 | .Open "GET", "http://trirand.com/blog/phpjqgrid/examples/jsonp/getjsonp.php?qwery=longorders&rows=1000", True 71 | .Send 72 | Do Until .ReadyState = 4: DoEvents: Loop 73 | sJSONString = .ResponseText 74 | End With 75 | ' Parse JSON response 76 | JSON.Parse sJSONString, vJSON, sState 77 | ' Check response validity 78 | Select Case True 79 | Case sState <> "Object" 80 | MsgBox "Invalid JSON response" 81 | Case Not vJSON.Exists("rows") 82 | MsgBox "JSON contains no rows" 83 | Case Else 84 | ' Convert JSON nested rows array to 2D Array and output to worksheet #1 85 | Output ThisWorkbook.Sheets(1), vJSON("rows") 86 | ' Flatten JSON 87 | JSON.Flatten vJSON, vFlat 88 | ' Convert to 2D Array and output to worksheet #2 89 | Output ThisWorkbook.Sheets(2), vFlat 90 | ' Serialize JSON and save to file 91 | CreateObject("Scripting.FileSystemObject") _ 92 | .OpenTextFile(ThisWorkbook.Path & "\sample.json", 2, True, -1) _ 93 | .Write JSON.Serialize(vJSON) 94 | ' Convert JSON to YAML and save to file 95 | CreateObject("Scripting.FileSystemObject") _ 96 | .OpenTextFile(ThisWorkbook.Path & "\sample.yaml", 2, True, -1) _ 97 | .Write JSON.ToYaml(vJSON) 98 | MsgBox "Completed" 99 | End Select 100 | 101 | End Sub 102 | 103 | Sub Output(oTarget As Worksheet, vJSON) 104 | 105 | Dim aData() 106 | Dim aHeader() 107 | 108 | ' Convert JSON to 2D Array 109 | JSON.ToArray vJSON, aData, aHeader 110 | ' Output to target worksheet range 111 | With oTarget 112 | .Activate 113 | .Cells.Delete 114 | With .Cells(1, 1) 115 | .Resize(1, UBound(aHeader) - LBound(aHeader) + 1).Value = aHeader 116 | .Offset(1, 0).Resize( _ 117 | UBound(aData, 1) - LBound(aData, 1) + 1, _ 118 | UBound(aData, 2) - LBound(aData, 2) + 1 _ 119 | ).Value = aData 120 | End With 121 | .Columns.AutoFit 122 | End With 123 | 124 | End Sub 125 | ``` 126 | 127 | ## More Examples 128 | You can find some usage examples on SO. 129 | 130 | ## Beta 131 | 132 | Here are some drafts being under development and not fully tested, any bugs detected and suggestions on improvement are welcome in [issues](https://github.com/omegastripes/VBA-JSON-parser/issues). 133 | 134 | ### Extension Beta 135 | 136 | [jsonExt.bas](https://github.com/omegastripes/VBA-JSON-parser/blob/master/Beta/jsonExt.bas). Some functions available as draft to add flexibility to computations and facilitate processing of JSON structure: 137 | 138 | **toArray()** - advanced converting JSON structure to 2d array, enhanced with options explicitly set columns names and order in the header and forbid or permit new columns addition.
139 | **filter()** - fetching elements from array or dictionary by conditions, set like `conds = Array(">=", Array("value", ".dimensions.height"), 15)`.
140 | **sort()** - ordering elements of array or dictionary by value of element by path, set like `".dimensions.height"`.
141 | **slice()** - fetching a part of array or dictionary by beginning and ending indexes.
142 | **selectElement()** - fetching an element from JSON structure by path, set like `".dimensions.height"`.
143 | **joinSubDicts()** - merging properties of subdictionaries from one dictionary to another dictionary.
144 | **joinDicts()** - merging properties from one dictionary to another dictionary.
145 | **nestedArraysToArray()** - converting nested 1d arrays representing table data with header array into array of dictionaries.
146 | 147 | ### JSON To XML DOM converter Beta 148 | 149 | [JSON2XML.bas](https://github.com/omegastripes/VBA-JSON-parser/blob/master/Beta/JSON2XML.bas). Converting JSON string to XML string and loading it into XML DOM (instead of building a structure of dictionaries and arrays) can significantly increase performance for large data sets. Further XML DOM data processing is not yet covered within current version, and can be implemented via DOM methods and XPath. 150 | 151 | ### Douglas Crockford json2.js implementation for VBA Beta 152 | 153 | **jsJsonParser** parser is essential for parsing large amounts of JSON data in VBA, it promptly parses strings up to 10 MB and even larger. This implementation built on [douglascrockford/JSON-js](https://github.com/douglascrockford/JSON-js/blob/master/json2.js), native JS code runs on IE JScript engine hosted by htmlfile ActiveX. Parser is wrapped into class module to make it possible to instantiate htmlfile object and create environment for JS execution in Class_Initialize event prior to parsing methods call. 154 | 155 | There are two methods available to parse JSON string: `parseToJs(sample, success)` and `parseToVb sample, jsJsonData, result, success`, as follows from the names you can parse to native JS entities of JScriptTypeInfo type, or parse to VBA entities which are a structure of nested Dictionaries and Arrays as described in [Purpose and Features](https://github.com/omegastripes/VBA-JSON-parser#purpose-and-features) section. Access to native JS entities is possible using `jsGetProp()` and `jsGetType()` methods. For JS entities processing you have to have at least common knowledge of JavaScript Objects and Arrays. 156 | 157 | Also you can parse to JS entities first, then make some processing and finally convert to VBA entities by calling `parseToVb , jsJsonData, result, success` for further utilization. JS entities can be serialized to JSON string by `stringify(jsJsonData, spacer)` method, if you need to serialize VBA entities, then use `JSON.Serialize()` function from [JSON.bas module](https://github.com/omegastripes/VBA-JSON-parser/blob/master/JSON.bas). If you don't want to mess with JS entities, simply use `parseToVb sample, , result, success` method. Note that convertion to VBA entities will take extra time. 158 | 159 | There are few examples in jsJsonParser_v0.1.1.xlsm workbook of the [last release](https://github.com/omegastripes/VBA-JSON-parser/releases/) 160 | --------------------------------------------------------------------------------