在python

时间:2016-12-20 15:09:14

标签: python json

我定期从API中获取一些数据,并希望将JSON数据存储到数据库中以便以后访问和使用。

从API,我每次都会在此示例中获取数据:

'{"data": {"cursor": null, "files": {"nodes": [{u'code': u'BOPhmYQg5Vm', u'date': 1482244678,u'counts': 2, u'id': u'1409492981312099686'}, {u'code': u'g5VmBOPhmYQ', u'date': 1482244678,u'counts': 5, u'id': u'1209968614094929813'}]}}}'

我可以json_data = json.loads(above_data)然后抓取nodes作为nodes_data = json_data["data"]["files"]["nodes"],其中会列出nodes

我想将此nodes数据存储到data = Column(db.Text)类型的数据库列Text中。每次节点列表中将有10-15个值。

我如何存储?有多个nodes我需要它以后我可以在我的数据库中添加/添加更多nodes到已有的data列。

虽然我想做json.loads(db_data_col)以便我获得有效的json并且可以循环遍历所有nodes以获取内部数据并在以后使用。

我对如何在db中存储以及稍后以有效的json格式访问感到困惑。

编辑1:使用Sqlite进行测试。以后可以使用PostgresSQL。 Text列类型是主要观点。

2 个答案:

答案 0 :(得分:3)

如果您使用的是Django 1.8,您可以创建自己的模型字段,可以存储json。该类将确保您具有正确的JSON格式。

import json
from django.db import models

class JsonField(models.TextField):
    """
    Stores json-able python objects as json.
    """
    def get_db_prep_value(self, value, connection, prepared=False):
        try:
            return json.dumps(value)
        except TypeError:
            BAD_DATA.error(
                "cannot serialize %s to store in a JsonField", str(value)
            )
            return ""

    def from_db_value(self, value, expression, connection, context):
        if value == "":
            return None
        try:
            return json.loads(value)
        except TypeError:
            BAD_DATA.error("cannot load dictionary field -- type error")
            return None

答案 1 :(得分:2)

我找到了一种将JSON数据存储到DB中的方法。由于我从远程服务访问nodes,每次请求都返回list个节点,我需要构建适当的json来存储/检索db。

Say API将json文本返回为:'{"cursor": null, "nodes" = [{"name": "Test1", "value: 1}, {"name": "Test2", "value: 2}, ...]}'

所以,首先我们需要访问节点列表:

data = json.loads(api_data)
nodes = data['nodes']

现在,要进入DB列,我们需要执行以下操作:

str_data = json.dumps({"nodes": nodes})

因此,str_data将返回一个有效的字符串/缓冲区,我们可以使用"nodes"密钥将其存储到DB中。

对于DB列的第二次或连续输入,我们将执行以下操作:

# get data string from DB column and load into json
db_data = json.loads(db_col_data)
# get new/latest 'nodes' data from api as explained above
# append this data to 'db_data' json as
latest_data = db_data["nodes"] + new_api_nodes
# now add this data back to column after json.dumps()
db_col_data = json.dumps(latest_data)
# add to DB col and DB commit

这是在添加/删除json并保持正确格式的同时从DB加载/转储数据的正确方法。

谢谢!

相关问题