- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 postgresql 9.4(又名 mongodb killer ;-))和这个简单的模式:
CREATE TABLE test (id SERIAL, name text, misc jsonb);
现在我填充它,如果我进行选择,它将显示类似
的内容id | name | misc
1 | user1 | { "age" : 23, "size" : "M" }
2 | user2 | { "age" : 30, "size" : "XL" }
现在,如果我用 psycopg2 发出请求,
cur.execute("SELECT * FROM test;")
rows = list(cur)
我会结束
[ { 'id' : 1, 'name' : 'user1', 'misc' : '{ "age" : 23, "size" : "M" }' },
{ 'id2' : 2, 'name' : 'user2', 'misc' : '{ "age" : 30, "size" : "XL' }' }]
你会告诉我有什么问题吗?杂项是 str 类型。我希望它被识别为 json 并转换为 Python 字典。
在 psycopg2 文档 ( psycopg2/extras page ) 中指出“从数据库读取,json 值将自动转换为 Python 对象。”
使用 RealDictCursor 似乎不是这样。这意味着我无法访问 rows[0]['misc']['age'] 因为它会很方便...
好的,我可以手动做
for r in rows:
r['misc'] = json.loads(r['misc'])
但如果我能避免这种情况,因为有更好的解决方案...
附言。拥有 1500+ 代表的人可以创建 postgresql9.4 标签 ;-)
最佳答案
当前的 psycopg 版本 (2.5.3) 不知道 jsonb 类型的 oid。为了支持它,调用就足够了:
import psycopg2.extras
psycopg2.extras.register_json(oid=3802, array_oid=3807, globally=True)
一次在你的项目中。
您可以在 this ML message 中找到更多信息.
关于postgresql - 带有 psycopg2 RealDictCursor 的 jsonb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25263736/
AFAIU 和文档中,RealDictCursor 是一个专门的 DictCursor,它允许仅从键(又名列名)访问列,而 DictCursor允许从键或索引号访问数据。 我想知道如果 DictCur
我有一个 postgresql 9.4(又名 mongodb killer ;-))和这个简单的模式: CREATE TABLE test (id SERIAL, name text, misc js
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) dict_cur.execute("SELECT colum
我是一名优秀的程序员,十分优秀!