简体   繁体   English

使用 sqlalchemy 将 json 文件的某些键的值写入 postgresql 表

[英]Writing the value of certain keys of a json file to a postgresql table with sqlalchemy

How do I write the values of certain keys contained in the result.json file to the table I created.如何将 result.json 文件中包含的某些键的值写入我创建的表中。 the values in the certain keys will be written in the columns I have created.某些键中的值将写入我创建的列中。 I have id, title, score columns in my table.我的表中有 id、title、score 列。 I want to write the value opposite the title key in the title column and the value opposite the score key in the score column.我想在标题列中写与标题键相对的值,在分数列中写与分数键相对的值。

result.son file:结果.son 文件:

[
  {
    "title": "Street Basketball Association",
    "appId": "com.sba.android.googleplay",
    "url": "https://play.google.com/store/apps/details?id=com.sba.android.googleplay",
    "icon": "https://play-lh.googleusercontent.com/a17t8kK_A4TMJtV0l6oTGzOvLbu_QlnKiWZM3L4RB-xprNL57z1YAJlal9ewEPrWxrW3=w240-h480-rw",
    "developer": "ShakaChen",
    "currency": "USD",
    "price": 0,
    "free": true,
    "summary": "We will bring you the hottest basketball game experience.You can invite other players to a real-time online competition or rank up while playing various league, cups and events in spectacular arenas.",
    "scoreText": "4.0",
    "score": 4.315321
  }
]

the name of my database is test :in this database, I have a table with one test_table .我的数据库的名称是test :在这个数据库中,我有一个带有一个test_table的表。

My code:我的代码:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSON


app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username:password@localhost:5432/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)


class Test(test.Model):
    __tablename__ = 'test_table'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    score = db.Column(db.Float)

with open('./result.json') as my_file:
    dicts = load(my_file)

for dictionary in dicts:
    test_data = Test(app_name=dictionary['title'],
                                    developer=dictionary['developer'],
                                    score=dictionary['score'])

    db.session.add(test_data)
    db.session.commit()

First of all, your Person model has score field set to db.Integer , yet in the data you're getting, score is set to float .首先,您的Person model 的score字段设置为db.Integer ,但在您获得的数据中, score设置为float This will cause a Data MisMatch error.这将导致Data MisMatch错误。

Now, for the json part.现在,对于json零件。

You import the load method from the json module so you're able to convert json objects to Python dicts .您从json模块导入load方法,以便能够将json对象转换为Python dicts

from json import load

You open your file, preferably inside a context so the file gets automatically released once you're done with it.你打开你的文件,最好是在一个context ,这样文件在你完成后会自动释放。

with open('result.json') as my_file:
    dicts = load(my_file)

Now dicts is a list of dict objects on which you can operate.现在dicts是您可以操作的dict对象的列表。 You initiate a new instance of your Person db.model and assign each of the values to the appropriate field.您启动Person db.model的新实例并将每个值分配给适当的字段。

for dictionary in dicts: #Remember, you have a list of dicts.
    person = Person(app_id=dictionary['appId'], 
                  title=dictionary['title'], score=dictionary['score']) 
                  #Remember to set the score field to the appropriate datatype. 
                  #i.e: db.Float
    db.session.add(person) #Add your new person instance to the session.
    db.session.commit() #Persists the user to your database.

Update : Based from what I understood from your comment.更新:根据我从您的评论中了解到的情况。 You can set your db.Model as follows:您可以设置您的db.Model如下:

class Person(db.Model):
    __tablename__ = 'test'
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    app_id = db.Column(db.String(10), index=True)
    title = db.Column(db.String(255))
    score = db.Column(db.Float) #You're getting float values.

Now, you have the id set by your database and the app_id from the json file.现在,您有了数据库设置的idapp_id文件中的json And you always have the option to search by the former or the latter.而且您始终可以选择按前者或后者进行搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM