2015-07-22 67 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)))) 
相关问题