Racket 中的 REST API JSON 解析

Boh*_*nov 3 rest scheme json racket

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

"{\"word\": \"a\", \"desc\": \"b\"}"
Run Code Online (Sandbox Code Playgroud)

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

 (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 
       ...]
      )
     )
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,请求正文和硬编码的 JSON 是相同的。

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

 "{\"word\": \"a\", \"desc\": \"b\"}"
 {"word": "a", "desc": "b"}
 #t#f
 #hasheq((desc . b) (word . a))
 #t
 desc = b
 word = a
Run Code Online (Sandbox Code Playgroud)

Body是一体传输的,甚至转化为jsexpr,但仍然不是hash!因此,我无法对 post-data-expr1 使用哈希方法。

从此类 jsexpr 获取哈希值的最佳方法是什么?或者我应该使用另一种方法来获取键/值?

问候。

soe*_*ard 5

这个程序:

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

有输出:

'#hasheq((desc . "b") (word . "a"))
'#hasheq((desc . "b") (word . "a"))
Run Code Online (Sandbox Code Playgroud)

这意味着bytes->jsexpr应该可以工作。

你能改变一下吗:

 (define post-data (request-post-data/raw req))
 (display post-data)
 (newline)
Run Code Online (Sandbox Code Playgroud)

 (define post-data (request-post-data/raw req))
 (write post-data)
 (newline)
Run Code Online (Sandbox Code Playgroud)

我感觉这个字节串的内容和你后面使用的略有不同。

笔记:

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

> (displayln "{\"word\": \"a\", \"desc\": \"b\"}")
{"word": "a", "desc": "b"}
Run Code Online (Sandbox Code Playgroud)

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