你如何在球拍中将一个 jsexpr 附加到另一个 jsexpr

How do you append one jsexpr to another jsexpr in racket

我正在尝试将两个 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)))))

库生成不可变哈希表而不是列表,并且没有 hash-append 这样的东西。定义 hash-append 的最简单方法似乎涉及将所有哈希值转换为列表,然后再返回:

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

如果相同的标识符出现两次,则以第二次出现为准 第一个,如果您直接使用重复键评估 JSON,这与 JavaScript 会做的事情相同。

使用两个文件的内容列表进行简单附加:

(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))))