[英]Dynamanically add column(s) and insert values into a Sqlite TABLE from json objects
我正在使用 Python tweepy
库来废弃和收集推文数据以用于研究目的。 具体是使用tweepy.StreamingClient
class 从 stream 获取推文。 返回的数据是json
object,其元素取决于检索到的推文帖子可用的数据字段。
例如,有一次我收到了json
object ,其中包含以下几个元素:
{
"data": {
"author_id": "1556031969062010881",
"created_at": "2022-08-18T01:51:03.000Z",
"geo": {
"place_id": "006c6743642cb09c"
},
"id": "1560081812604469248",
"text": "Some text ..."
},
"matching_rules": [
{
"id": "1560077018183630848",
"tag": "some-key-words"
}
]
}
有时,返回 object 并扩展元素,例如:
{
"data": {
"author_id": "1118585113657389059",
"created_at": "2022-08-18T01:55:05.000Z",
"geo": {
"place_id": "00611f1548c7bdef"
},
"id": "1560082826153828357",
"referenced_tweets": [
{
"type": "replied_to",
"id": "1559833610697539585"
}
],
"text": "hhh personality"
},
"includes": {
"tweets": [
{
"author_id": "1462820862969716746",
"created_at": "2022-08-17T09:24:47.000Z",
"geo": {},
"id": "1559833610697539585",
"text": "What do men like in a woman?"
}
]
},
"matching_rules": [
{
"id": "1560077018183630848",
"tag": "some-key-words"
}
]
}
在更复杂的json
object 中,有时嵌套元素如下:
{
"data": {
"author_id": "1461871206425108480",
"created_at": "2022-08-17T23:19:14.000Z",
"geo": {
"coordinates": {
"type": "Point",
"coordinates": [
-0.1094,
51.5141
]
},
"place_id": "3eb2c704fe8a50cb"
},
"id": "1560043605762392066",
"text": "#bitemoji #me #thinkingaboutmydeceasedKoreanGrandmother #ALWAYS #DAILY #AMEN @ London, United Kingdom "
},
"matching_rules": [
{
"id": "1560042248007458817",
"tag": "some-key-words"
}
]
}
我对data
的元素和matching_rules
组感兴趣,后者仅包含 2 个元素,但前者( data
)组元素可以更改或扩展。 例如,在这项工作中特别感兴趣的geo
元素,它具有:
"geo": {
"place_id": "some-value"
},
在第一个和第二个返回的对象中,但是在第三个 object 中,它像这样展开:
"geo": {
"coordinates": {
"type": "Point",
"coordinates": [
-0.1094,
51.5141
]
},
"place_id": "3eb2c704fe8a50cb"
},
所以我们必须创建 2 个新列来存储type": "Point",
和"coordinates": [-0.1094,51.5141]
值。
然而,我们可以在第二个 object 中看到"includes"
组中的另一个geo
元素。 这完全不需要,但可能会“混淆”我们的搜索。
在这种情况下,如何动态存储添加列和最初的“窄”起始表并插入值?
我使用sqlite
插入来自传感器的值,这是我使用以下语法的物联网研究:
con = sqlite3.connect("db-name.db")
while True:
# values received
query = "INSERT INTO table_name(columns-names) VALUES(?,?,?,?,?,?,?,?,?)"
data = (variable)
cur = con.execute(query, data)
con.commit()
con.close()
然而,在这种情况下,表格列的动态增长和/或某些元素的值变化(例如geo
让我更加困惑!
虽然您可以动态更改表,但以与行相同的方式处理列并不是一个好主意。 您可以使用以下选项之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.