我想把两个json文件合并在一起。如果我直接这么做,就会有偏执的问题。我想让它们两个concactenate作为两个jsexp,然后写入输出文件。你怎么能在球拍上打两支球拍?
(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)))))发布于 2015-07-22 08:46:14
库生成不可变的哈希表而不是列表,并且没有类似于hash-append的东西。定义hash-append的最简单方法似乎是将所有散列转换为列表,然后再返回:
(define (hash-append . hashes)
(make-immutable-hasheq
(apply append
(map hash->list hashes))))如果同一个标识符出现两次,那么第二个实例将取代第一个标识符,这与JavaScript使用重复键计算JSON时所做的相同。
发布于 2015-07-22 08:46:46
使用两个文件的内容列表简单地追加:
(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))))https://stackoverflow.com/questions/31556932
复制相似问题