Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amber and localstorage, asJSON?

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

http://www.json.org

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.
like image 503
z-- Avatar asked Mar 24 '14 08:03

z--


1 Answers

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.

like image 81
z-- Avatar answered Oct 23 '22 08:10

z--