2015-07-22 68 views
1

我想concactenate兩個json文件在一起。如果我直接做他們然後 有pamentalhesis的問題。我希望他們兩個concactenate作爲兩個jsexp,然後寫入輸出文件。你如何在球拍中簡化兩個jsexpr?你怎麼追加一個jsexpr到另一個jsexpr在球拍

(define (write-or-append-to-json destfile newfile) 

(define full-json 
    (lambda (json-str) 
    (let ((jsexp (string->jsexpr json-str))) 
    (hash-refs jsexp '())))) 

(let ((dest-json #f) 
     (new-json #f)) 
(set! new-json (full-json (file->string newfile))) 

(if (file-exists? destfile)  

    (begin ;insert insert-what of newjson into destjson 
     (set! dest-json (full-json (file->string destfile))) 
     (delete-file destfile) 

     ;;Append two jsexp together. i.e. append new-json info to dest-json) 
    (begin ;json does not exist, simply create it   
     (write-json new-json destfile))))) 

回答

1

庫產生不變的哈希表來代替列表,並沒有爲hash-append沒有這樣的事情。定義hash-append最簡單的方法似乎再次涉及到將所有哈希到列表,然後:如果同一標識出現兩次

(define (hash-append . hashes) 
    (make-immutable-hasheq 
     (apply append 
      (map hash->list hashes)))) 

,那麼二審取代 第一,這是同樣的事情的JavaScript如果您直接使用重複鍵評估JSON,則會執行此操作。使用的兩個文件的內容列表

2

簡單的追加:

(define (concat-json-files file1 file2 outfile) 
    (define json1 (call-with-input-file* file1 read-json)) 
    (define json2 (call-with-input-file* file2 read-json)) 
    (define out (list json1 json2)) 
    (call-with-output-file* outfile #:exists 'truncate 
    (λ(o) (write-json out o)))) 

如果要合併兩個JSON對象,你需要做的是對球拍一側的兩個哈希表。快速示例:

(define (concat-json-files file1 file2 outfile) 
    (define json1 (call-with-input-file* file1 read-json)) 
    (define json2 (call-with-input-file* file2 read-json)) 
    (define out (make-hash)) 
    (for* ([json (in-list (list json1 json2))] 
     [(k v) (in-hash json)]) 
    (hash-set! out k v)) 
    (call-with-output-file* outfile #:exists 'truncate 
    (λ(o) (write-json out o))))