SlideShare ist ein Scribd-Unternehmen logo
1 von 12
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 cJobject
VBA 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").addArr
ay
Add an array element
object
f.push({family:{name:”Flintstone”,wi
fe:”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
Portability
The 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
Iteration
How to iterate through cJobject children.
Examples - vba
for each joc in job.children
Debug.Print job.key,job.value
next joc
Examples - 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
Recursion
Since 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
Extensibility
Easy to extend with powerful capabilities
Examples
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.name
Find 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
Chaining
The cJobect is designed to be chainable
Examples – 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 classes
Creating 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 arguments
It‟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 options
reshapeMelt "{'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 recovery
Like 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
Summary
These examples show some of the capabilities of
cJObect and bringing a JSON capability to Excel
For more detail, and to download see Excel Liberation

Weitere ähnliche Inhalte

Was ist angesagt?

リッチなドメインモデル 名前探し
リッチなドメインモデル 名前探しリッチなドメインモデル 名前探し
リッチなドメインモデル 名前探し増田 亨
 
Java開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyJava開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyYasuharu Nakano
 
商流物流金流.pdf
商流物流金流.pdf商流物流金流.pdf
商流物流金流.pdfZenji Kanzaki
 
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Springドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring増田 亨
 
ドメイン駆動設計に15年取り組んでわかったこと
ドメイン駆動設計に15年取り組んでわかったことドメイン駆動設計に15年取り組んでわかったこと
ドメイン駆動設計に15年取り組んでわかったこと増田 亨
 
C#メタプログラミング概略 in 2021
C#メタプログラミング概略 in 2021C#メタプログラミング概略 in 2021
C#メタプログラミング概略 in 2021Atsushi Nakamura
 
C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)Takuya Kawabe
 
3週連続DDDその1 ドメイン駆動設計の基本を理解する
3週連続DDDその1  ドメイン駆動設計の基本を理解する3週連続DDDその1  ドメイン駆動設計の基本を理解する
3週連続DDDその1 ドメイン駆動設計の基本を理解する増田 亨
 
「自分のとこでは動くけど…」を無くす devcontainer
「自分のとこでは動くけど…」を無くす devcontainer「自分のとこでは動くけど…」を無くす devcontainer
「自分のとこでは動くけど…」を無くす devcontainerYuta Matsumura
 
徳丸本に載っていないWebアプリケーションセキュリティ
徳丸本に載っていないWebアプリケーションセキュリティ徳丸本に載っていないWebアプリケーションセキュリティ
徳丸本に載っていないWebアプリケーションセキュリティHiroshi Tokumaru
 
ドメイン駆動設計サンプルコードの徹底解説
ドメイン駆動設計サンプルコードの徹底解説ドメイン駆動設計サンプルコードの徹底解説
ドメイン駆動設計サンプルコードの徹底解説増田 亨
 
20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと
20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと
20220319_新卒から活躍し続けるエンジニアが大切にしている5つのことLIFULL Co., Ltd.
 
WebRTCのオーディオ処理の謎、誰か教えて!
WebRTCのオーディオ処理の謎、誰か教えて!WebRTCのオーディオ処理の謎、誰か教えて!
WebRTCのオーディオ処理の謎、誰か教えて!mganeko
 
Unityでオニオンアーキテクチャ
UnityでオニオンアーキテクチャUnityでオニオンアーキテクチャ
Unityでオニオンアーキテクチャtorisoup
 
データモデリング・テクニック
データモデリング・テクニックデータモデリング・テクニック
データモデリング・テクニックHidekatsu Izuno
 
ドメイン駆動設計の正しい歩き方
ドメイン駆動設計の正しい歩き方ドメイン駆動設計の正しい歩き方
ドメイン駆動設計の正しい歩き方増田 亨
 
DDD x CQRS 更新系と参照系で異なるORMを併用して上手くいった話
DDD x CQRS   更新系と参照系で異なるORMを併用して上手くいった話DDD x CQRS   更新系と参照系で異なるORMを併用して上手くいった話
DDD x CQRS 更新系と参照系で異なるORMを併用して上手くいった話Koichiro Matsuoka
 
モジュールの凝集度・結合度・インタフェース
モジュールの凝集度・結合度・インタフェースモジュールの凝集度・結合度・インタフェース
モジュールの凝集度・結合度・インタフェースHajime Yanagawa
 
Goの時刻に関するテスト
Goの時刻に関するテストGoの時刻に関するテスト
Goの時刻に関するテストKentaro Kawano
 
CODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato Kinugawa
CODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato KinugawaCODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato Kinugawa
CODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato KinugawaCODE BLUE
 

Was ist angesagt? (20)

リッチなドメインモデル 名前探し
リッチなドメインモデル 名前探しリッチなドメインモデル 名前探し
リッチなドメインモデル 名前探し
 
Java開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyJava開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovy
 
商流物流金流.pdf
商流物流金流.pdf商流物流金流.pdf
商流物流金流.pdf
 
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Springドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
 
ドメイン駆動設計に15年取り組んでわかったこと
ドメイン駆動設計に15年取り組んでわかったことドメイン駆動設計に15年取り組んでわかったこと
ドメイン駆動設計に15年取り組んでわかったこと
 
C#メタプログラミング概略 in 2021
C#メタプログラミング概略 in 2021C#メタプログラミング概略 in 2021
C#メタプログラミング概略 in 2021
 
C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)
 
3週連続DDDその1 ドメイン駆動設計の基本を理解する
3週連続DDDその1  ドメイン駆動設計の基本を理解する3週連続DDDその1  ドメイン駆動設計の基本を理解する
3週連続DDDその1 ドメイン駆動設計の基本を理解する
 
「自分のとこでは動くけど…」を無くす devcontainer
「自分のとこでは動くけど…」を無くす devcontainer「自分のとこでは動くけど…」を無くす devcontainer
「自分のとこでは動くけど…」を無くす devcontainer
 
徳丸本に載っていないWebアプリケーションセキュリティ
徳丸本に載っていないWebアプリケーションセキュリティ徳丸本に載っていないWebアプリケーションセキュリティ
徳丸本に載っていないWebアプリケーションセキュリティ
 
ドメイン駆動設計サンプルコードの徹底解説
ドメイン駆動設計サンプルコードの徹底解説ドメイン駆動設計サンプルコードの徹底解説
ドメイン駆動設計サンプルコードの徹底解説
 
20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと
20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと
20220319_新卒から活躍し続けるエンジニアが大切にしている5つのこと
 
WebRTCのオーディオ処理の謎、誰か教えて!
WebRTCのオーディオ処理の謎、誰か教えて!WebRTCのオーディオ処理の謎、誰か教えて!
WebRTCのオーディオ処理の謎、誰か教えて!
 
Unityでオニオンアーキテクチャ
UnityでオニオンアーキテクチャUnityでオニオンアーキテクチャ
Unityでオニオンアーキテクチャ
 
データモデリング・テクニック
データモデリング・テクニックデータモデリング・テクニック
データモデリング・テクニック
 
ドメイン駆動設計の正しい歩き方
ドメイン駆動設計の正しい歩き方ドメイン駆動設計の正しい歩き方
ドメイン駆動設計の正しい歩き方
 
DDD x CQRS 更新系と参照系で異なるORMを併用して上手くいった話
DDD x CQRS   更新系と参照系で異なるORMを併用して上手くいった話DDD x CQRS   更新系と参照系で異なるORMを併用して上手くいった話
DDD x CQRS 更新系と参照系で異なるORMを併用して上手くいった話
 
モジュールの凝集度・結合度・インタフェース
モジュールの凝集度・結合度・インタフェースモジュールの凝集度・結合度・インタフェース
モジュールの凝集度・結合度・インタフェース
 
Goの時刻に関するテスト
Goの時刻に関するテストGoの時刻に関するテスト
Goの時刻に関するテスト
 
CODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato Kinugawa
CODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato KinugawaCODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato Kinugawa
CODE BLUE 2014 : バグハンターの愉しみ by キヌガワマサト Masato Kinugawa
 

Ähnlich wie Javascript like objects and JSON processing in VBA

Javascript the New Parts v2
Javascript the New Parts v2Javascript the New Parts v2
Javascript the New Parts v2Federico Galassi
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016DesertJames
 
The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181Mahmoud Samir Fayed
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using RoomNelson Glauber Leal
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)William Narmontas
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesomePiotr Miazga
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsAnton Astashov
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript WorkshopPamela Fox
 
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...amit kuraria
 
Processing XML and Spreadsheet data in Go
Processing XML and Spreadsheet data in GoProcessing XML and Spreadsheet data in Go
Processing XML and Spreadsheet data in GoRi Xu
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 

Ähnlich wie Javascript like objects and JSON processing in VBA (20)

QTP
QTPQTP
QTP
 
Js types
Js typesJs types
Js types
 
Polyglot Persistence
Polyglot PersistencePolyglot Persistence
Polyglot Persistence
 
Javascript the New Parts v2
Javascript the New Parts v2Javascript the New Parts v2
Javascript the New Parts v2
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
 
The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
 
Week3
Week3Week3
Week3
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScripts
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
 
Processing XML and Spreadsheet data in Go
Processing XML and Spreadsheet data in GoProcessing XML and Spreadsheet data in Go
Processing XML and Spreadsheet data in Go
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Ch2
Ch2Ch2
Ch2
 

Mehr von Bruce McPherson

Do something in 5 with gas 8-copy between databases
Do something in 5 with gas 8-copy between databasesDo something in 5 with gas 8-copy between databases
Do something in 5 with gas 8-copy between databasesBruce McPherson
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Bruce McPherson
 
Do something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterDo something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterBruce McPherson
 
Do something in 5 with gas 7-email log
Do something in 5 with gas 7-email logDo something in 5 with gas 7-email log
Do something in 5 with gas 7-email logBruce McPherson
 
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Bruce McPherson
 
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheetDo something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheetBruce McPherson
 
Do something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing appDo something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing appBruce McPherson
 
Do something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseDo something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseBruce McPherson
 
Do something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as databaseDo something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as databaseBruce McPherson
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed versionBruce McPherson
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionBruce McPherson
 
Using script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and ExcelUsing script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and ExcelBruce McPherson
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerBruce McPherson
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 

Mehr von Bruce McPherson (16)

Do something in 5 with gas 8-copy between databases
Do something in 5 with gas 8-copy between databasesDo something in 5 with gas 8-copy between databases
Do something in 5 with gas 8-copy between databases
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2
 
Goa tutorial
Goa tutorialGoa tutorial
Goa tutorial
 
Do something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterDo something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilter
 
Do something in 5 with gas 7-email log
Do something in 5 with gas 7-email logDo something in 5 with gas 7-email log
Do something in 5 with gas 7-email log
 
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
 
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheetDo something in 5 with gas 4- Get your analytics profiles to a spreadsheet
Do something in 5 with gas 4- Get your analytics profiles to a spreadsheet
 
Do something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing appDo something in 5 with gas 3-simple invoicing app
Do something in 5 with gas 3-simple invoicing app
 
Do something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a databaseDo something in 5 with gas 2-graduate to a database
Do something in 5 with gas 2-graduate to a database
 
Do something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as databaseDo something in 5 minutes with gas 1-use spreadsheet as database
Do something in 5 minutes with gas 1-use spreadsheet as database
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstraction
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
Using script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and ExcelUsing script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and Excel
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 

Kürzlich hochgeladen

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Javascript like objects and JSON processing in VBA

  • 1. Javascript like objects and JSON processing in VBA cJobject primer from Excel Liberation
  • 2. 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
  • 3. Excel Liberation for details Javascript object versus cJobject VBA 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").addArr ay Add an array element object f.push({family:{name:”Flintstone”,wi fe:”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()
  • 4. Excel Liberation for details Portability The 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();
  • 5. Excel Liberation for details Iteration How to iterate through cJobject children. Examples - vba for each joc in job.children Debug.Print job.key,job.value next joc Examples - 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]); }
  • 6. Excel Liberation for details Recursion Since 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
  • 7. Excel Liberation for details Extensibility Easy to extend with powerful capabilities Examples 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.name Find 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 ......
  • 8. Excel Liberation for details Chaining The cJobect is designed to be chainable Examples – 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
  • 9. Excel Liberation for details Custom classes and sub classes Creating 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()
  • 10. Excel Liberation for details ‘Javascript like’ optional arguments It‟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 options reshapeMelt "{'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
  • 11. Excel Liberation for details Memory recovery Like 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
  • 12. Excel Liberation for details Summary These examples show some of the capabilities of cJObect and bringing a JSON capability to Excel For more detail, and to download see Excel Liberation