REST API JSON 在 Racket 中解析

REST API JSON Parsing in Racket

我出于教育目的在 Racket 中开发休息服务并面临 JSON 解析问题。 我有 POST 请求,正文如下

"{\"word\": \"a\", \"desc\": \"b\"}"

我也有此请求的请求处理程序,例如

 (define (add-word-req req)
     (define post-data (request-post-data/raw req))
     (display post-data)
     (newline)

     (define post-data-expr1 (bytes->jsexpr post-data))
     (display post-data-expr1)
     (newline)
     (display (jsexpr? post-data-expr1))
     (display (hash? post-data-expr1))
     (newline)

     (define post-data-expr (string->jsexpr "{\"word\": \"a\", \"desc\": \"b\"}"))
     (display post-data-expr)
     (newline)

     (display (hash? post-data-expr))
     (newline)

     (for (((key val) (in-hash post-data-expr)))
       (printf "~a = ~a~%" key val))

     (cond 
       [(jsexpr? post-data-expr)
       ;; some conditional work
       ...
      ]
       [else 
       ...]
      )
     )

如您所见,请求正文和硬编码 JSON 相同。

在处理请求时我得到下一个输出:

 "{\"word\": \"a\", \"desc\": \"b\"}"
 {"word": "a", "desc": "b"}
 #t#f
 #hasheq((desc . b) (word . a))
 #t
 desc = b
 word = a

body是一块传输的,甚至转成了jsexpr,还是不是hash!因此,我不能对 post-data-expr1.

使用哈希方法

从这样的 jsexpr 中获取哈希值的最佳方法是什么?或者我应该使用其他方法来获取key/values?

此致。

这个节目:

#lang racket
(require json)
(string->jsexpr "{\"word\": \"a\", \"desc\": \"b\"}")
(bytes->jsexpr #"{\"word\": \"a\", \"desc\": \"b\"}")

有输出:

'#hasheq((desc . "b") (word . "a"))
'#hasheq((desc . "b") (word . "a"))

这意味着 bytes->jsexpr 应该有效。

你能改变吗:

 (define post-data (request-post-data/raw req))
 (display post-data)
 (newline)

 (define post-data (request-post-data/raw req))
 (write post-data)
 (newline)

?

感觉字节串的内容和你后面用的略有不同

注:

> (displayln "{\\"word\\": \\"a\\", \\"desc\\": \\"b\\"}")
{\"word\": \"a\", \"desc\": \"b\"}

> (displayln "{\"word\": \"a\", \"desc\": \"b\"}")
{"word": "a", "desc": "b"}

您的 (display post-data-expr1) 的输出与上面的第一个交互匹配。因此,我的猜测是反斜杠和引号在您的输入中都被转义了。