我试图将两个json文件连接在一起。如果我直接这样做 有副作用的问题。我希望他们两个concactenate作为两个jsexp然后写入输出文件。你会如何在球拍中将两个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)))))
答案 0 :(得分: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对象,则需要在Racket端的两个哈希表上执行此操作。快速举例:
(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))))
答案 1 :(得分:1)
库生成不可变的哈希表而不是列表,并且没有hash-append
这样的东西。定义hash-append
的最简单方法似乎是将所有哈希值转换为列表然后再返回:
(define (hash-append . hashes)
(make-immutable-hasheq
(apply append
(map hash->list hashes))))
如果相同的标识符出现两次,则第二个实例取代 第一个,如果您直接使用重复键评估JSON,那将与JavaScript相同。