我想在数据库中插入大量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
列出一种插入多行的方法,其中: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格式。
看来我有两个选择:
按摩数据以适应
找到一个函数,让它保持原样。
我怀疑
insert-rows-into
做了我想做的,但我不太确定如何把它塞进里面。 最佳答案
这有用吗?
(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,")))
关于sql - 使用postmodern将json数据插入到postgresql数据库中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19825431/