I want to store with Amber (on-line IDE) an OrderedCollection in the localStorage of a web browser and later retrieve it.
| coll hcoll |
coll := OrderedCollection new.
coll add: 'abc'.
coll add: 'xon'.
hcoll := HashedCollection new.
hcoll at: 'en' put: 'English'.
hcoll at: 'fr' put: 'French'.
hcoll at: 'ge' put: 'German'.
coll add: hcoll.
localStorage is a key-value store in the browser. The values have to be strings.
localStorage setItem: 'coll' value: coll asJSONString.
"We set coll to nil to indicate that we
are going to retrieve it back from the localStorage"
coll := nil.
a printIt of the following
localStorage getItem: 'coll'
gives
'["abc","xon",{"en":"English","fr":"French","ge":"German"}]'
This is a JSON string.
How do I get back the OrderedCollection coll?
Use the JSON parser built into the browser
JSON parse: (localStorage getItem: 'coll')
The result of a printIt is
an Array ('abc' 'xon' [object Object])
and
(JSON parse: (localStorage getItem: 'coll')) class
is
Array
The third element of the Array
((JSON parse: (localStorage getItem: 'coll')) at: 3) class
is a
JSObjectProxy
How do I get back the Smalltalk representation for an arbitrary JSON object (containing JavaScript Arrays and Objects, OrderedCollections and HashedCollections, Dictionaries in Smalltalk)?
http://www.json.org
JSON is built on two structures:
A printIt of
SmalltalkImage current readJSObject:
(JSON parse: (localStorage getItem: 'coll'))
gives back
an Array ('abc' 'xon' a Dictionary ('en' -> 'English' , 'fr' -> 'French' , 'ge' -> 'German'))
Comment
(JSON parse: (localStorage getItem: 'coll'))
gives a JSProxyObject which is then converted to Amber objects by the method #readJSObject: . This method just redirects the call to an underlying JavaScript method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With