Tenesta ScriptForge.Dictionary

Ei ordliste er ei samling av nøkkelelementpar

Nøklar og element kan hentast, teljast, oppdaterast og mykje meir.

Tipsikon

Objekta LibreOffice Basic Collection har ikkje støtte for henting av nøklane.
I tillegg inneheld elementa berre primitive grunnleggjande datatypar, for eksempel datoar, tekst, tal og liknande.


Oppkall av tenester

Eksempelet nedføre opprettar myDict som ei tom ordbok.


    GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
    Dim myDict As Variant
    myDict = CreateScriptService("Dictionary")
  

Det vert tilrådd å frigje ressursar etter bruk:


     Set myDict = myDict.Dispose()
  

Eigenskapar

Namn

Skriveverna

Type

Beskriving

Count

Ja

Long

Talet på oppføringar i ordboka

Items

Ja

Matrise med variantar

Lista over elementa som ei eindimensjonal matrise

Keys

Ja

Matrise av strengar

Lista over nøklar som ei eindimensjonal matrise


Tipsikon

Eigenskapane Keys og Items returnerer deira respektive indhald i ei identisk rekkjefølgje. Rekkefølgja er ikkje relatert til rekkjefølgja sett ved opprettinga.


Eksempel:

Det neste eksempelet brukar eigenskapen Keys for gå gjennom alle nøklane i myDict fleire gonger.


    Dim a As Variant, b As String
    a = myDict.Keys
    For Each b In a
        MsgBox(myDict.Item(b))
    Next b
    

Metodar

Add
ConvertToArray
ConvertToJson
ConvertToPropertyValues

Exists
ImportFromJson
ImportFromPropertyValues
Item

Remove
RemoveAll
ReplaceItem
ReplaceKey


Add

Legg eit nytt nøkkelelementpar til ordboka. Returnerer Sann viss det lukkast.

Syntaks:


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

Parametrar:

Nøkkel: Strengverdi som vert brukt for å identifisera elementet. Nøkkelen skil ikkje mellom store og små bokstavar.

Element: Kva verdi som helst, også ei matrise, eit Basic-objekt, eit UNO-objekt, ei ordbok og så vidare.

Eksempel:


          Dim NewValue As Variant
          myDict.Add("NewKey", NewValue)
       
warning

Kvar nøkkel må vera unik i den same ordlista. Viss nøkkelen finst frå før i ordlista, vert det sett opp ein DUPLICATEKEYERROR. Nøklar som er laga av mellomromsteikn, vil setja opp feilen INVALIDKEYERROR.


ConvertToArray

Lagrar innhaldet i ordboka i ei to-kolonnars, null-basert matrise. Nøklane er lagra i den første kolonnen og elementa i den andre kolonnen.

Viss ordboka er tom, vil denne metoden returnere ei tom matrise.

Syntaks:


          myDict.ConvertToArray() As Variant
        

Eksempel:


        Dim myDict as Variant
        myDict = CreateScriptService("Dictionary")
        myDict.Add("a", 1)
        myDict.Add("b", 2)
        myDict.Add("c", 3)
        Dim arr as Variant
        arr = myDict.ConvertToArray()
        '(("a", 1), ("b", 2), ("c", 3))
      

ConvertToJson

Konverterer innhaldet i ordboka til tekst i JSON (JavaScript Object Notation).

Avgrensingar

Denne metoden har støtte for desse datatypane: String, Boolean, numbers, Null og Empty. Matriser som inneheld element av desse er også tillatne, kva dimensjon dei måtte ha. Datoar vert konverterte til strengar som vert brukte i matrisene. Andre datatypar vert konverterte til det dei er representert med i strengen ved hjelp av tenesta SF_String.Represent.

Syntaks:


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

Parametrar:

Innrykk: Når Indent er eit positivt tal eller ein tekst, vert JSON-matriseelement og objektledd skrivne ut med dette innrykket. Ein negativ verdi for Indent vil leggja til nye linjer utan innrykk. Standardverdien "" for Indent vel den mest kompakte representasjonen. Bruk av eit positivt heiltal for Indent vil setja inn så mange innrykk på nivået som talet seier. NårIndent er ein streng, for eksempel Chr(9 eller Tab(1), vert tabulator-teiknet brukt for innrykk.

Eksempel:


            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 myDict.ConvertToJson()    
            '{"p0": 12.5, "p1": "a string \u00e0\u00e9\"\u00ea", "p2": "2020-09-28", "p3": true, "p4": [1, 2, 3]}
        

ConvertToPropertyValues

Lagra innhaldet i ordlista i ei matrise av PropertyValues.

Kvar oppføring er ein com.sun.star.beans.PropertyValue. Nøkkelen er lagra i Name, elementet i Value.

Viss eitt av elementa har ein type Data, vert denne konvertert til ein com.sun.star.util.DateTime-struktur. Viss eitt av elementa er ei tom matrise, vert det konvertert til Null. Sluttmatrisa er tom når ordboka er tom.

Syntaks:


          myDict.ConvertToPropertyValues() As Variant
        

Eksempel:


          Dim myDict as Variant
          myDict = CreateScriptService("Dictionary")
          ' Legg nokre eigenskapar til i ordboka
          myDict.Add("Color", "Blue")
          myDict.Add("Width", 20)
          ' Konverterer til ei matrise av objekta PropertyValue
          Dim prop as Variant
          prop = myDict.ConvertToPropertyValues()
        
tip

Mange tenester og metodar i UNO-biblioteket tek inn parameterar som er representerte med strukturen PropertyValue, som er ein del av LibreOffice API-en.


Exists

Bestemmer om det finst ein nøkkel i ordboka.

Syntaks:


          myDict.Exists(Key As String) As Boolean
        

Parametrar:

Nøkkel : Nøkkelen som skal slåast opp i ordboka.

Eksempel:


          Dim myDict as Variant
          myDict = CreateScriptService("Dictionary")
          ' Legg nokre eigenskapar til i ordboka
          myDict.Add("Color", "Blue")
          myDict.Add("Width", 20)
          '(...)
          If Not myDict.Exists("Size") Then
             MsgBox "You have to provide a Size value"
          End If
        

ImportFromJson

Adds the content of a JSON (JavaScript Object Notation) string 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 matches one of these patterns: YYYY-MM-DD, HH:MM:SS or YYYY-MM-DD HH:MM:SS.

Syntaks:


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

Parametrar:

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), repeated keys will raise an error. Beware that dictionary keys are not case-sensitive while names are case-sensitive in JSON strings.

Eksempel:


            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 imported as Empty values.
        

ImportFromPropertyValues

Inserts the contents of an array of PropertyValue objects into the current dictionary. PropertyValue Names are used as Keys in the dictionary, whereas Values contain the corresponding values. Returns True if successful.

Syntaks:


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

Parametrar:

PropertyValues : A zero-based 1 dimensional array containing com.sun.star.beans.PropertyValue objects. This parameter may also be a single PropertyValue object not contained in an Array.

Overwrite : When True, entries with same name may exist in the dictionary and their values are overwritten. When False (default), repeated keys will raise an error. Note that dictionary keys are not case-sensitive, whereas names are case-sensitive in sets of property values.

Eksempel:


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

Item

Retrieves an existing dictionary entry based on its key. Returns the value of the item if successful, otherwise returns Empty.

Syntaks:


          myDict.Item(Key As String) As Variant
        

Parametrar:

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

Eksempel:

The following example iterates over all keys in the dictionary and uses the Item method to access their values.


          Dim myDict as Variant, k as Variant, allKeys as Variant
          myDict = CreateScriptService("Dictionary")
          myDict.Add("key1", 100)
          myDict.Add("key2", 200)
          myDict.Add("key3", 300)
          allKeys = myDict.Keys
          For Each k in allKeys
             MsgBox(myDict.Item(k))
          Next k
       

Remove

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

Syntaks:


          myDict.Remove(Key As String) As Boolean
        

Parametrar:

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

Eksempel:


          myDict.Add("key1", 100)
          myDict.Add("key2", 200)
          myDict.Add("key3", 300)
          MsgBox(myDict.Count) 'Prints "3"
          myDict.Remove("key2")
          MsgBox(myDict.Count) 'Prints "2"
       

RemoveAll

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

Syntaks:


          myDict.RemoveAll() As Boolean
        

Eksempel:


          myDict.Add("key1", 100)
          myDict.Add("key2", 200)
          myDict.Add("key3", 300)
          MsgBox(myDict.Count) 'Prints "3"
          myDict.RemoveAll()
          MsgBox(myDict.Count) 'Prints "0"
        

ReplaceItem

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

Syntaks:


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

Parametrar:

Key : String value representing the key whose value will be replaced. Not case-sensitive. If the key does not exist in the dictionary, a UNKNOWNKEYERROR error is raised.

Value : The new value of the item referred to with the Key parameter.

Eksempel:


          myDict.Add("a", 1)
          MsgBox(myDict.Item("a")) 'Prints "1"
          myDict.ReplaceItem("a", 100)
          MsgBox(myDict.Item("a")) ' Prints "100"
       

ReplaceKey

Replaces an existing key in the dictionary by a new key. The item value is left unchanged. Returns True if successful.

Syntaks:


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

Parametrar:

Key : String value representing the key to be replaced. Not case-sensitive. If the key does not exist in the dictionary, a UNKNOWNKEYERROR error is raised.

Value : String value for the new key. Not case-sensitive. If the new key already exists in the dictionary, a DUPLICATEKEYERROR error is raised.

Eksempel:


          myDict.Add("oldKey", 100)
          MsgBox(myDict.Item("oldKey")) 'Prints "100"
          myDict.ReplaceKey("oldKey", "newKey")
          MsgBox(myDict.Item("newKey")) ' Prints "100"
       
warning

Alle Basic-rutinane og -identifikatorane i ScriptForge som vert innleidde med understrek «_» er reserverte for internt bruk. Dei er ikkje tenkt brukte i Basic-makroar.