I want to store with Amber (on-line IDE) an OrderedCollection in the localStorage of a web browser and later retrieve it.
Creating a test data object
| 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.
Storing the test data object in localStorage
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.
Getting back the stored value
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
Question
How do I get back the Smalltalk representation for an arbitrary JSON object (containing JavaScript Arrays and Objects, OrderedCollections and HashedCollections, Dictionaries in Smalltalk)?
Note
JSON is built on two structures:
- A collection of name/value pairs. In various languages, this is realized as an object, dictionary, hash table, or associative array.
- An ordered list of values. In many languages, this is realized as an array, list, or sequence.