简体   繁体   English

琥珀和本地存储,作为JSON?

[英]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. 我想在Web浏览器的localStorage中存储Amber( 在线IDE )和OrderedCollection,然后检索它。

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中

localStorage is a key-value store in the browser. localStorage是浏览器中的键值存储。 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 以下的printIt

localStorage getItem: 'coll' 

gives

 '["abc","xon",{"en":"English","fr":"French","ge":"German"}]' 

This is a JSON string. 这是一个JSON字符串。

How do I get back the OrderedCollection coll ? 如何取回OrderedCollection coll

Use the JSON parser built into the browser 使用浏览器中内置的JSON解析器

JSON parse: (localStorage getItem: 'coll')

The result of a printIt is printIt的结果是

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)? 如何获取任意JSON对象的Smalltalk表示(包含JavaScript数组和对象,OrderedCollections和HashedCollections,Smalltalk中的字典)?

Note 注意

http://www.json.org http://www.json.org

JSON is built on two structures: JSON基于两种结构:

  • 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. 在许多语言中,这被实现为数组,列表或序列。

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: . 给出一个JSProxyObject,然后通过方法#readJSObject:将其转换为Amber对象。 This method just redirects the call to an underlying JavaScript method. 此方法只是将调用重定向到基础JavaScript方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM