2016-01-20 17 views
1

我想分析ndjson(換行分隔的JSON)數據NeoJSON上菲羅Smalltalk的。如何分析ndjson在菲羅與NeoJSON

ndjson數據是這樣的:

{"smalltalk": "cool"} 
{"pharo": "cooler"} 

目前,我在我的文件流轉換爲字符串,將它在新行,然後解析使用NeoJSON的單件。這似乎使用了一個不必要的(和非常巨大的)內存和時間,可能是因爲將流轉換爲字符串,反之亦然。什麼是完成這項任務的有效方法?

如果你看一下樣本數據:NYPL-publicdomain: pd_items_1.ndjson

回答

3

這個斯文(NeoJSON的作者)在菲羅用戶郵件列表的答案(他是不是在SO):

讀「格式」很簡單,只需繼續做#next每個JSON表達式(空格被忽略)。

| data reader | 
data := '{"smalltalk": "cool"} 
{"pharo": "cooler"}'. 
reader := NeoJSONReader on: data readStream. 
Array streamContents: [ :out | 
    [ reader atEnd ] whileFalse: [ out nextPut: reader next ] ]. 

防止中間數據結構也很容易,使用流媒體。

| client reader data networkStream | 
(client := ZnClient new) 
    streaming: true; 
    url: 'https://github.com/NYPL-publicdomain/data-and-utilities/blob/master/items/pd_items_1.ndjson?raw=true'; 
    get. 
networkStream := ZnCharacterReadStream on: client contents. 
reader := NeoJSONReader on: networkStream. 
data := Array streamContents: [ :out | 
    [ reader atEnd ] whileFalse: [ out nextPut: reader next ] ]. 
client close. 
data. 

花了幾秒鐘的時間,畢竟50K的項目在網絡上是80MB +。

2

請問,如果你打開一個新的ReadWriteStream它的工作,先寫到$ {到它,然後流用逗號分隔的原始數據流中的所有內容到它,然後寫一個尾隨$}。產生的流應該適合NeoJSON ...? 這可能是一個STTCPW攻擊的問題,但W是impprtant ;-)它應該更快,更少的內存消耗,因爲NeoJSON只會做一個傳球。它。

+0

我想,你的意思是$ [和$]做一個數組?這很好。 – MartinW

+0

我想你是對的;-) –

1

你可以嘗試這樣的事:

| input reader | 
input := FileStream readOnlyFileNamed: 'resources/pd_items_1.ndjson.txt'. 
[ 
Array 
    streamContents: [ :strm | 
     | ln | 
     [ (ln := input nextLine) isNil ] 
      whileFalse: [ strm nextPut: (NeoJSONReader fromString: ln) ] ] ] timeToRun. 

除非這是你嘗試過什麼已經...