reading-and-writing.scm 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. (use-modules (ice-9 textual-ports) ; for textual reading and writing procedures
  2. (ice-9 binary-ports) ; not sure if needed
  3. (ice-9 rdelim) ; for `eof-object?`
  4. (ice-9 optargs) ; for keyword arguments
  5. (srfi srfi-1)
  6. (json))
  7. ;; not really working well.
  8. ;; for now just make it a string and print that.
  9. #;(define (print-json the-json)
  10. (define (iter json-part)
  11. (cond
  12. [(hash-table? json-part)
  13. (let ([alistified (hash-map->list cons json-part)])
  14. (map (λ (assoc)
  15. (cons (car assoc) (iter (cdr assoc))))
  16. alistified))]
  17. [else (list json-part)]))
  18. (display (simple-format #f "~a\n" (iter the-json))))
  19. (define* (print-json the-json)
  20. (display
  21. (simple-format #f "~a\n" (scm->json-string the-json #:escape #f #:pretty #t))))
  22. (define* (get-string-from-file file-path #:key (encoding "UTF-8"))
  23. (call-with-input-file file-path
  24. (λ (port)
  25. (set-port-encoding! port encoding)
  26. (get-string-all port))))
  27. (define* (put-string-to-file file-path string #:key (encoding "UTF-8") (mode 'replace))
  28. (call-with-output-file file-path
  29. (λ (port)
  30. (set-port-encoding! port encoding)
  31. (put-string port
  32. (cond [(eq? mode 'append)
  33. (string-append (get-string-from-file
  34. file-path
  35. #:encoding encoding)
  36. "\n"
  37. string)]
  38. [(equal? mode 'replace) string]
  39. [else string])))))
  40. (define* (get-json-from-file file-path)
  41. (json-string->scm (get-string-from-file file-path)))
  42. (define* (put-json-to-file file-path the-json
  43. #:key
  44. (escape-slashes #f)
  45. (pretty #f)
  46. (escape-unicode #f))
  47. (put-string-to-file file-path
  48. (scm->json-string the-json
  49. #:escape escape-slashes
  50. #:pretty pretty
  51. ;; do not escape unicode chars
  52. #:unicode escape-unicode)))