如何解析Clojure中的URL参数? [英] How to parse URL parameters in Clojure?

查看:33
本文介绍了如何解析Clojure中的URL参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有请求 "size=3&mean=1&sd=3&type=pdf&distr=normal" 编写函数 (defn request->map [request] ...) 接受这个请求并且返回一个地图 {:size 3, :mean 1, :sd 3, :type pdf, :distr normal}

If I have the request "size=3&mean=1&sd=3&type=pdf&distr=normal" what's the idiomatic way of writing the function (defn request->map [request] ...) that takes this request and returns a map {:size 3, :mean 1, :sd 3, :type pdf, :distr normal}

这是我的尝试(使用 clojure.walk 和 clojure.string):

Here is my attempt (using clojure.walk and clojure.string):

(defn request-to-map
   [request]
   (keywordize-keys
      (apply hash-map
             (split request #"(&|=)"))))

我对其他人如何解决这个问题很感兴趣.

I am interested in how others would solve this problem.

推荐答案

您可以使用许多 Java 库轻松完成此操作.除非我仔细阅读 URI 规范并确保我没有遗漏任何边缘情况(例如,参数在查询中出现两次,但具有不同的值),否则我会犹豫是否尝试推出自己的解析器.这使用 jetty-util:

You can do this easily with a number of Java libraries. I'd be hesitant to try to roll my own parser unless I read the URI specs carefully and made sure I wasn't missing any edge cases (e.g. params appearing in the query twice with different values). This uses jetty-util:

(import '[org.eclipse.jetty.util UrlEncoded MultiMap])

(defn parse-query-string [query]
  (let [params (MultiMap.)]
    (UrlEncoded/decodeTo query params "UTF-8")
    (into {} params)))

user> (parse-query-string "size=3&mean=1&sd=3&type=pdf&distr=normal")
{"sd" "3", "mean" "1", "distr" "normal", "type" "pdf", "size" "3"}

这篇关于如何解析Clojure中的URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆