【问题标题】:store Json field in an external file (.json) by python通过python将Json字段存储在外部文件(.json)中
【发布时间】:2019-07-22 09:40:39
【问题描述】:

我在 postgresql v11 中的表包含一个 json 字段,我会使用 python (lib: SQLALSHEMY) 将此数据存储在外部文件 JSON 中。我试着去做,但我遇到了困难:

import psycopg2
from app import db
from models import Geotab 

from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy.sql import select




try:
connection = psycopg2.connect(user = "postgres",
                              password = "admin",
                              host = "127.0.0.1",
                              port = "5432",
                              database = "catalogue")
cursor = connection.cursor()
# Print PostgreSQL Connection properties
print ( connection.get_dsn_parameters(),"\n")
# Print PostgreSQL version
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record,"\n")
except (Exception, psycopg2.Error) as error :
 print ("Error while connecting to PostgreSQL", error)



data=db.session.query(Geotab).\
   filter(Geotab.dataJson[''])   #.astext.cast(JSON))
print (data)

执行代码后:

user=postgres 密码=admin 主机=127.0.0.1 端口=5432 dbname=catalogue {'user':'postgres','dbname':'catalogue','host':'127.0.0.1','port':'5432','tty':'','options':'',' sslmode':'prefer','sslcompression':'0','krbsrvname':'postgres','target_session_attrs':'any'} 您已连接到 - ('PostgreSQL 11.4,由 Visual C++ build 1914 编译, 64 位',) 选择 geocat.id 作为 geocat_id、geocat.url 作为 geocat_url、geocat.date 作为 geocat_date, geocat."dataJson" AS "geocat_dataJson" 来自地理猫 WHERE geocat."dataJson" -> %(dataJson_1)s

geotab:models.py 中的类 dataJson : 列类型 json 表名:geocat

请帮帮我

【问题讨论】:

  • 我不知道如何选择dataJson列的数据并将其存储在外部文件中?
  • 事实上,我阅读了 sqlalshemy lib 并尝试修改语法,但每次都有障碍。

标签: postgresql json python


【解决方案1】:

我找到了解决办法,谢谢:

from sqlalchemy import create_engine
from app import db
from models import Geotab 
from sqlalchemy import Integer
import json

from sqlalchemy.dialects.postgresql import JSON


engine = create_engine('postgresql://postgres:admin@127.0.0.1:5432/catalogue', echo = 
True)
conn = engine.connect()


data=db.session.query(Geotab).\
  filter(Geotab.id==1)
print (data)
result = db.session.query(Geotab).all()

metadata={}
for row in result:
   print ("dataJson:",row.dataJson)
   metadata=row.dataJson
with open('metadata.json', 'w') as outfile:
  json.dump(metadata, outfile)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2018-11-03
    相关资源
    最近更新 更多