使用postmodern将json数据插入postgresql db

时间:2013-11-07 00:00:02

标签: sql json postgresql lisp common-lisp

我想在我的数据库中插入大量JSON数据。

[{
    "term": "wine",
    "name": "Bubba Wine & Spirits",
    "address": "1234 N San Fake Rd,"
}, {
    "term": "wine",
    "name": "Wine Shop",
    "address": "123 N Not Real Blvd,"
}]

我使用cl-json转换为lisp对象。

(defvar *data*
  (decode-json (open "my-json-file.json")))

结果如下:

(((:TERM . "wine") (:NAME . "Bubba Wine & Spirits")
  (:ADDRESS . "1234 N San Fake Rd,"))
 ((:TERM . "wine") (:NAME . "Wine Shop")
  (:ADDRESS . "123 N Not Real Blvd,")))

Postmodern列出了一种在insert-rows-into处插入多行的方法:https://sites.google.com/site/sabraonthehill/postmodern-examples/postmodern-insert#multiple-row-inserts

(:insert-rows-into 'table :columns 'a 'b :values '((10 20) (30 40)))

这不是默认的JSON格式。

看起来我有两个选择:

  1. 按摩数据以适合
  2. 找一个按原样运行的函数。
  3. 我怀疑:insert-rows-into做了我想要的但是我不太确定如何把它塞进那里。

2 个答案:

答案 0 :(得分:4)

这有帮助吗?

(defun compose (&rest fns)
  (lambda (x)
    (reduce #'funcall fns :initial-value x :from-end t)))

(defun quotify (x)
  `',x)

(defun guess-columns (data *package*)
  (mapcar (compose #'quotify #'intern #'symbol-name #'first) (first data)))

(defun guess-values (data)
  (loop for x in data collect (mapcar #'cdr x)))

(defun insert-rows (data package)
  `(:insert-rows-into 'table :columns ,@(guess-columns data package)
                  :values ',(guess-values data)))

使用insert-rows致电*data*会得到结果

(:INSERT-ROWS-INTO 'TABLE :COLUMNS 'TERM 'NAME 'ADDRESS :VALUES
 '(("wine" "Bubba Wine & Spirits" "1234 N San Fake Rd,")
   ("wine" "Wine Shop" "123 N Not Real Blvd,")))

答案 1 :(得分:1)

您可以修改解析器的行为以生成所需的输出,如下所示:

(defun json->insert ()
  (labels ((%string->symbol (s) (intern (string-upcase s))))
    (let (keys values row)
      (json:bind-custom-vars
          (:object-key
           (lambda (key)
             (unless (member key keys :test #'equal)
               (push key keys)))
           :object-value
           (lambda (value) (push value row))
           :end-of-object
           (lambda () (setf values (cons row values) row nil)))
        (json:decode-json-from-string
         "[{
    \"term\": \"wine\",
    \"name\": \"Bubba Wine & Spirits\",
    \"address\": \"1234 N San Fake Rd,\"
    }, {
    \"term\": \"wine\",
    \"name\": \"Wine Shop\",
    \"address\": \"123 N Not Real Blvd,\"
    }]"))
      (list (mapcar #'%string->symbol keys) values))))

;; (json->insert)
;; ((ADDRESS NAME TERM)
;;  (("123 N Not Real Blvd," "Wine Shop" "wine")
;;   ("1234 N San Fake Rd," "Bubba Wine & Spirits" "wine")))

但是,在我看来,cl-json过度设计,你可能会更好地使用像cl-yacc这样的东西构建临时解析器并完成它。我知道建议重新发明一些东西是一件奇怪的事情,特别是当它已经有了它的工具时,但这就是我最终在某些时候所做的事情(我需要一个拉解析器)。但我鼓励你运用自己的判断力。