写入 JSON 文件时出现问题 - 无效密钥

问题描述 投票:0回答:1

上下文:我的教授希望我为他的班级设置一个自动评分器(用于 Gradescope),而我在将结果放入 results.json 文件时遇到一些困难

错误:

write-json: expected argument of type <legal JSON key value>; given: "tests"
  context...:
   .../json/main.rkt:132:2: loop
   .../json/main.rkt:94:0: write-json*
   .../source/autograder.rkt:48:0: grade
   body of '#%mzc:autograder

代码:

(define results-file "../results/results.json")

(define (starter-data-entry name) 
  (make-hash `(("score" . 0) ("max_score" . 0) ("output" . "Will be manually graded") ("name" . ,name))))

(define results-data
  (make-hash `(("tests" . ,(for/list ([i (in-range 1 13)])
                                 (starter-data-entry (format "question~a" i)))))))

(define (grade-question fn-hw fn-sol input-cases id max-score)
  (let* ([results
          (for/fold ([acc (cons 0 0)]) ; acc is a pair (total-tests . passed-tests)
                    ([input (in-list input-cases)])
            (let* ([hw-result (apply fn-hw input)]
                   [sol-result (apply fn-sol input)]
                   [total-tests (car acc)]
                   [passed-tests (cdr acc)])
              (if (equal? hw-result sol-result)
                  (cons (+ total-tests 1) (+ passed-tests 1))
                  (cons (+ total-tests 1) passed-tests))))]
         [total-tests (car results)]
         [passed-tests (cdr results)]
         [score (floor (* max-score (/ passed-tests total-tests)))]
         [output (format "Passed ~a out of ~a test cases." passed-tests total-tests)])
    (hash-update! results-data "tests"
        (lambda (tests)
            (map (lambda (test)
                (if (equal? (hash-ref test "name") id)
                    (hash "name" id "score" score "max_score" max-score "output" output)
                    test))
                tests)))
    (void)))

(define (write-json-file filepath data)
    (call-with-output-file filepath
        (lambda (out)
            (write-json data out))
        #:exists 'replace))

(define (grade)
    (grade-question hw:sequence sol:sequence (sequence-test-case-generator 50) "question1" 7)
    (grade-question hw:string-append-map sol:string-append-map (string-append-map-test-case-generator 50) "question2" 7)
    ; ... more calls to grade-question, not really relevant

    (display results-data)
    (write-json-file results-file results-data)
)

(grade)

我有一个可行的解决方案(但它非常磨损 - 将结果数据哈希打印到 std-out,然后将其传递到解析字符串并写入 json 文件的 python 文件中),但我只是好奇我是什么我做错了,因为我真的无法弄清楚。

我的球拍知识有很多漏洞,而且我对此并不精通,所以也许这是由于我没有意识到的一个愚蠢的错误;我知道这不是写入文件的权限问题,并且 results.json 文件已经存在。我也尝试将模板“结果数据”写入 json 文件 - 这给了我同样的错误 - 所以哈希更新!成绩问题不应该成为问题的一部分。

json racket
1个回答
0
投票

Racket 的主要 JSON 库将 JSON 对象表示为哈希表,其中 符号作为键,而不是字符串。

小例子:

#lang racket/base

(require json)

(define (starter-data-entry name) 
  (hasheq 'score 0 'max_score 0 'output "Will be manually graded" 'name name))

(write-json (starter-data-entry "foo"))
© www.soinside.com 2019 - 2024. All rights reserved.