Racket写入results.json时出现无效键错误,求问题排查
解决Racket中write-json写入"tests"键时报错的问题
问题原因
你遇到的write-json: expected argument of type <legal JSON key value>; given: "tests"错误,核心是传入write-json的哈希表使用了符号类型的键,而非字符串类型。Racket里用make-hash '((tests . value))这种方式初始化时,键会被解析为符号'tests,但JSON规范要求对象键必须是字符串,write-json无法将符号直接作为合法JSON键处理。
解决方案
1. 初始化哈希表时用字符串键
- 用
make-hash创建:
(define results-data (make-hash (list (cons "tests" '()))))
- 更简洁的
hash函数写法(Racket 6.9+支持):
(define results-data (hash "tests" '()))
2. 转换现有符号键哈希表为字符串键
如果已经有符号键的哈希表,可批量转换:
(define (symbol-hash->string-hash h) (for/hash ([(k v) (in-hash h)]) (values (symbol->string k) v))) (define fixed-results (symbol-hash->string-hash results-data))
3. 标准写入代码示例
确保调用write-json时传入合法的JSON表达式:
(require json) (call-with-output-file "results.json" (λ (out) (write-json results-data out)) #:exists 'replace)
验证方法
运行最小测试案例验证:
(require json) (define test-data (hash "tests" (list (hash "name" "Test 1" "score" 10)))) (call-with-output-file "test.json" (λ (out) (write-json test-data out)) #:exists 'replace)
若能生成合法JSON文件,说明问题已解决。
内容的提问来源于stack exchange,提问作者Thezi
相关产品推荐
相关产品推荐

