Javascript - Módulo 8: LocalStorage, iFrames, Origin policy y JSON
Javascript like objects and JSON processing in VBA
-
Upload
bruce-mcpherson -
Category
Technology
-
view
40.679 -
download
6
description
Transcript of Javascript like objects and JSON processing in VBA
Javascript like objects and JSON processing in VBA
cJobject primer from Excel Liberation
Excel Liberation for details
cJobject purpose
The Excel/VBA model is optimized for 2 dimensions (rows/columns) – or at best 3 (sheets/rows/columns)
{ "Flintstone Characters": { "families": [ { "family": { "name": "FlintStone", "wife": "Wilma", "husband": "Fred", "kids": [ "Pebbles" ], "pets": [ "Baby Puss", "Dino", "Doozy" ] } }, { "family": { "name": "Rubble", "wife": "Betty", "husband": "Barney", "kids": [ "Bam Bam" ], "pets": [ "Hoppy" ] } } ] }}
Data from web sources can be any depth. VBA lacked the capability to deal with either the format or the structure of JSON data. cJobject provides both the structure and data handling capability
Excel Liberation for details
Javascript object versus cJobjectVBA lacks the syntax to express such an object as
concisely as javascript,but a similar capability can be achieved with cJobjectAction javaScript cJobject
New object var job = {}; Set job = new cJobect
Create from JSON var job = JSON.parse(str); Set job = JSONParse(str)
Add a property job["Flintstone Characters”] = null;
job.add ("Flintstone Characters”)
Add an array var f = job["Flintstone Characters”] ={families:[]};
Set f = job.child("Flintstone Characters").add("families").addArray
Add an array element object
f.push({family:{name:”Flintstone”,wife:”Wilma”,husband:”Fred”});
With f.add.add("family") .add "name", "FlintStone" .add "wife", "Wilma" .add "husband", "Fred“End with
Convert to JSON JSON.stringify(job); JSONstringify(job)..or.. job.stringify()
Excel Liberation for details
PortabilityThe Google Apps Script version of cJobject has the same
syntax (allowing for minor javaScript/VBA linguistic differences)
Examples – Google Apps Script
var job = new cJobject();
job.add ("Flintstone Characters”);
var f = job.child("Flintstone Characters").add("families").addArray();
The cJobject is not really needed in GAS, since js can do this natively. But using cJobject in GAS allows portability to and from VBA. There are also native conversions for GAS available
Examples – Google Apps Script
var job = fromNative(someObject);
var someObject = job.toNative();
Excel Liberation for details
IterationHow to iterate through cJobject children. Examples - vba
for each joc in job.children
Debug.Print job.key,job.value
next jocExamples - gas
job.children().forEach( function (joc) {
Logger.log (job.key() + “,” + job.value());
});
Equivalent in native javaScript
Examples
var jsObject = job.toNative();
for (k in jsObject ) {
console.log(k + “,” + jsObject [k]);
}
Excel Liberation for details
RecursionSince cJobjects are of inderminate depth, recursion is used internally in the
class and they are ideally suited for recursive usage. Here’s an example of traversing and printing an entire object tree irrespective of the data structure.
Examples
Public Function printFlint(Optional job As cJobject = Nothing, _
Optional depth As Long = 0)
Dim joc As cJobject
If (job Is Nothing) Then Set job = getFlintsoneCharacters()
Debug.Print Space(depth); job.key; ":"; job.value
depth = depth + 2
For Each joc In job.children
depth = printFlint(joc, depth)
Next joc
printFlint = depth - 2
End Function
Flintstone Characters: families: 1: family: name:FlintStone wife:Wilma husband:Fred kids: 1:Pebbles pets: saber tooth tiger:Baby Puss dinosaur type dog thing:Dino dodo bird:Doozy 2: family: name:Rubble wife:Betty husband:Barney kids: 1:Bam Bam pets: kangaroo type thing:Hoppy
Excel Liberation for details
ExtensibilityEasy to extend with powerful capabilitiesExamples
Populate a data set with JSON data
dSet.populateJSON jobject, Range("json1!$a$1")Read a worksheet into a dset and convert it to JSON
dSet.populateData( Range("jSon2!$a$1"), , , , , , True).jObject.stringify()Get the fullkey of any item
job.fullKey() – eg Flintstones characters.1.family.nameFind a property somewhere
set wilma = job.find(“Wilma”)Make a treeview from a cJobject contents to display on a form
set t= job. toTreeView(treeViewObject)Access data returned from a rest API query
With restQuery(worksheetName, "my society", , "postcode", _
, , , False, False)
For Each job In .jObject.children ......
Excel Liberation for details
ChainingThe cJobect is designed to be chainableExamples – VBA
With .add.add("module") .add "name", module.name .add "kind", module.textKind With .add("procedures").addArray For Each procedure In module.procedures With .add.add("procedure") .add "name", procedure.name .add "scope", procedure.scope .add "kind", procedure.procTextKind .add "returns", procedure.procReturns .add "lineCount", procedure.lineCount .add "declaration", procedure.declaration With .add("arguments").addArray For Each argument In procedure.arguments With .add.add("argument") .add "name", argument.name .add "optional", argument.isOptional .add "default", argument.default .add "argtype", argument.argType End With Next argument End With End With Next procedure End With End With
Excel Liberation for details
Custom classes and sub classesCreating classes in VBA requires preknowledge about the class and its
properties. The cJobject can be used to create classes ‘on the fly’ to avoid cluttering the source code with many small classes
Examples
With job.init(Nothing, "Flintstone Characters").add("families").addArray
With .add.add("family")
.add "name", "FlintStone"
.add "wife", "Wilma"
.add "husband", "Fred"
With .add("kids").addArray
.add , "Pebbles"
End With
With .add("pets").addArray
.add "saber tooth tiger", "Baby Puss"
.add "dinosaur type dog thing", "Dino"
.add "dodo bird", "Doozy"
End With
End With
End with
Set clone = job.clone()
Excel Liberation for details
‘Javascript like’ optional argumentsIt’s very useful in javascript to be able to pass a single argument to a function
containing options and other data. The cJobject allows you do the something similar in VBA
Examples
.. Calling with a couple of non default optionsreshapeMelt "{'outputSheet':'meltOut','id':['id','time']}“-------------Public Function rOptionDefaults() As String ‘ the default options.. rOptionDefaults = _ "{'complain':true, 'inputSheet':'" & ActiveSheet.name & "'," & _ "'variableColumn' : 'variable', 'valueColumn' : 'value', 'id':['id'] ," & _ "'outputSheet': 'rOutputData' , 'clearContents':true}"End Function
Public Function reshapeMelt(options As String) As cDataSet‘... Applies default options and meges with given options Set jArgs = optionsExtend(options, rOptionDefaults) ' use the options... With jArgs If .toString("inputsheet") = .toString("outputsheet") Then MsgBox ("Reading and writing to the same sheet - not allowed") Exit Function End If End With
Excel Liberation for details
Memory recoveryLike many objects with recursive linking,
memory will not be recovered by the VBA garbage collector simply by going out of scope. A teardown is provided, and should be used for efficient memory recovery.
Examples
With JSONparse(str)
for each joc in .children
Debug.Print joc.value
next joc
.teardown
End With
Excel Liberation for details
SummaryThese examples show some of the capabilities
of cJObect and bringing a JSON capability to Excel
For more detail, and to download see Excel Liberation