ScriptForge.Dictionary service /text/sbasic/shared/03/sf_dictionary.xhp
Dictionary service API;DateTime API;PropertyValue

ScriptForge.Dictionary service

A dictionary is a collection of key-item pairs The key is a case-insensitive string Items may be of any type
Keys and items can be retrieved, counted, updated, and much more. %PRODUCTNAME Basic Collection object does not support the retrieval of the keys.
Additionally its items contain only primitive Basic data types such as dates, text, numbers, and the like.

Service invocation

GlobalScope.BasicLibraries.loadLibrary("ScriptForge") Dim myDict As Variant myDict = CreateScriptService("Dictionary") It is recommended to free resources after use: Set myDict = myDict.Dispose()

Properties

Name Readonly Argument Type Description Count Yes Long The actual number of entries in the dictionary Item Yes Key As String Variant The value of the item related to Key
Empty if not found
Items Yes Array of Variants The list of items as a one dimension array Keys Yes Array of Strings The list of keys as a one dimension array
The Keys and Items properties return their respective contents, using an identical ordering.
The order is unrelated to the creation sequence.

Dim a As Variant, b As String a = myDict.Keys For Each b In a ' ... Next b Methods Add

ConvertToArray
ConvertToJson
ConvertToPropertyValues
Exists

ImportFromJson
ImportFromPropertyValues
Item
Remove
RemoveAll
ReplaceItem
ReplaceKey
Add -------------------------------------------------------------------------------------------------------------------------- Dictionary service;Add

Add

Add a new key-item pair into the dictionary. Returns True if successful.

myDict.Add(Key As String, Item As Variant) As Boolean

Key : Not case-sensitive. Must not yet exist in the dictionary, otherwise a DUPLICATEKEYERROR error is generated. Spaces only generate a INVALIDKEYERROR error. Item : Any value, including an array, a Basic object, a UNO object, a dictionary, ...

Dim NewValue As Variant myDict.Add("NewKey", NewValue)
ConvertToArray -------------------------------------------------------------------------------------------------------------------------- Dictionary service;ConvertToArray

ConvertToArray

Store the content of the dictionary in a two-columns zero-based array. The key is stored in the first column, the item is stored in the second column.
The resulting array is empty when the dictionary is empty.

myDict.ConvertToArray() As Variant
ConvertToJson --------------------------------------------------------------------------------------------------------------------- Dictionary service;ConvertToJson

ConvertToJson

Convert the content of the dictionary to JSON (JavaScript Object Notation) text.

Limitations

Allowed data types are: String, Boolean, numbers, Null and Empty. Arrays containing items of those types are allowed, whatever their dimensions. Dates are converted into strings but not within arrays where they are forbidden. Other data types are converted to their string representation (cfr. SF_String.Represent).

myDict.ConvertToJson([Indent As Variant]) As String

Indent : When Indent is a positive number or a text, JSON array elements and object members are pretty-printed with that indent level. A negative Indent value solely insert new lines. Indent default value "" selects the most compact representation. Using a positive integer for Indent indents that many spaces per level. When Indent is a string, such as Chr(9) or Tab(1), the tab sign is used to indent each level.

myDict.Add("p0", 12.5) myDict.Add("p1", "a string àé""ê") myDict.Add("p2", DateSerial(2020,9,28)) myDict.Add("p3", True) myDict.Add("p4", Array(1,2,3)) MsgBox a.ConvertToJson() ' {"p0": 12.5, "p1": "a string \u00e0\u00e9\"\u00ea", "p2": "2020-09-28", "p3": true, "p4": [1, 2, 3]}
ConvertToPropertyValues ----------------------------------------------------------------------------------------------------------------------- Dictionary service;ConvertToPropertyValues

ConvertToPropertyValues

Store the content of the dictionary in an array of PropertyValues.
Each entry in the array is a com.sun.star.beans.PropertyValue. The key is stored in Name, the item is stored in Value.
If one of the items has a type Date, it is converted to a com.sun.star.util.DateTime structure.
If one of the items is an empty array, it is converted to Null.
The resulting array is empty when the dictionary is empty.

myDict.ConvertToPropertyValues() As Variant
Exists -------------------------------------------------------------------------------------------------------------------------- Dictionary service;Exists

Exists

Determine if a key exists in the dictionary.

myDict.Exists(Key As String) As Boolean

Key : The key to check.

If Not myDict.Exists("newkey") Then ' You may add it safely to the dictionary EndIf
ImportFromJson --------------------------------------------------------------------------------------------------------------------- Dictionary service;ImportFromJson

ImportFromJson

Add the content of a JSON (JavaScript Object Notation) text into the current dictionary. Returns True if successful.

Limitations

The JSON string may contain numbers, text, booleans, null values and arrays containing those types. It must not contain JSON objects namely sub-dictionaries. An attempt is made to convert text to date if the item fits one of these patterns: YYYY-MM-DD, HH:MM:SS or YYYY-MM-DD HH:MM:SS.

myDict.ImportFromJson(InputStr As String, [Overwrite As Boolean]) As Boolean

InputStr : The string to import. Overwrite : when True, entries with same name may exist in the dictionary and their values are overwritten. When False (default), synonyms raise an error. Note that dictionary keys are not case-sensitive while names are case-sensitive in JSON strings.

Dim s As String s = "{'firstName': 'John','lastName': 'Smith','isAlive': true,'age': 66, 'birth': '1954-09-28 20:15:00'" _ & ",'address': {'streetAddress': '21 2nd Street','city': 'New York','state': 'NY','postalCode': '10021-3100'}" _ & ",'phoneNumbers': [{'type': 'home','number': '212 555-1234'},{'type': 'office','number': '646 555-4567'}]" _ & ",'children': ['Q','M','G','T'],'spouse': null}" s = Replace(s, "'", """") myDict.ImportFromJson(s, OverWrite := True) ' The (sub)-dictionaries "address" and "phoneNumbers(0) and (1) are reduced to Empty.
ImportFromPropertyValues --------------------------------------------------------------------------------------------------------------------- Dictionary service;ImportFromPropertyValues

ImportFromPropertyValues

Insert the content of an array of PropertyValues into the current dictionary. Names contain the new keys, values contain the new items. Returns True if successful.

myDict.ImportFromPropertyValues(PropertyValues As Variant [, Overwrite As Boolean]) As Boolean

PropertyValues : a zero-based 1 dimension array. Each entry is a UNO object of type com.sun.star.beans.PropertyValue. The argument may also be a single item. Overwrite : when True, entries with same name may exist in the dictionary and their values are overwritten. When False (default), synonyms raise an error. Note that dictionary keys are not case-sensitive while names are case-sensitive in sets of property values.

Dim vProp As New com.sun.star.beans.PropertyValue vProp.Name = "prop" : vProp.Value = CDateToUnoDateTime(Now) myDict.ImportFromPropertyValues(vProp, Overwrite := True)
Remove -------------------------------------------------------------------------------------------------------------------------- Dictionary service;Remove

Remove

Remove an existing dictionary entry based on its key. Returns True if successful.

myDict.Remove(Key As String) As Boolean

Key : Not case-sensitive. Must exist in the dictionary, otherwise a UNKNOWNKEYERROR error is generated.

myDict.Remove("OldKey")
RemoveAll -------------------------------------------------------------------------------------------------------------------------- Dictionary service;RemoveAll

RemoveAll

Remove all the entries from the dictionary. Returns True if successful.

myDict.RemoveAll() As Boolean
ReplaceItem -------------------------------------------------------------------------------------------------------------------------- Dictionary service;ReplaceItem

ReplaceItem

Replace an existing item value based on its key. Returns True if successful.

myDict.ReplaceItem(Key As String, Value As Variant) As Boolean

Key : Not case-sensitive. Must exist in the dictionary, otherwise a UNKNOWNKEYERROR error is generated. Value : The new value of the item part of the dictionary entry.

Dim NewValue As Variant myDict.ReplaceItem("ExistingKey", NewValue)
ReplaceKey -------------------------------------------------------------------------------------------------------------------------- Dictionary service;ReplaceKey

ReplaceKey

Replace an existing key with a new value. The item part is left unchanged. Returns True if successful.

myDict.ReplaceKey(Key As String, Value As String) As Boolean

Key : Not case-sensitive. Must exist in the dictionary, otherwise a UNKNOWNKEYERROR error is generated. Value : Not case-sensitive. Must exist in the dictionary, otherwise a DUPLICATEKEYERROR error is generated.

myDict.ReplaceKey("OldKey", "NewKey")