为了教育目的,我正在开发Racket中的rest服务,并面临着JSON解析的问题。我有以下要求
"{\"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身体是一个整体传输,甚至转化成jsexpr,但它仍然不是哈希!正因为如此,我不能使用散列方法来处理后数据-expr1。
从这样的jsexpr中获取散列的最佳方法是什么?还是应该使用另一种方法来获取键/值?
致以问候。
发布于 2015-07-14 17:02:27
这个项目:
#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)的输出与上面的第一个交互匹配。因此,我的猜测是,反斜杠和引号都在您的输入中转义。
https://stackoverflow.com/questions/31412685
复制相似问题