首页 > 解决方案 > Python SQLite3在JSON文件中提取键和值

问题描述

我正在尝试提取 JSON 文件的键和值。但是,我无法提取正确的键和值。我必须在 SQLite 中提取并创建一个模式。

这是 JSON 文件的示例:

"entities": {"hashtags": [{"text": "#Hello world", "indices": [0, 19]}], "symbols": [], "user_mentions": [], "urls": [{"url": "www.co/DtjRrIzPTK"................

这是我的代码:

f = open('tweet.json',)
data = json.load(f)
for index, i in enumerate(data):
    entities = i['entities']
    tweet_id = i['id']
    types = list(entities.keys())
    for t in types:
        if t in entities_types:
            if entities[t] != []:
                for index,(key,value) in enumerate(entities[t][0].items()):
                    if index == 0:
                        type = key
                        type_value =  i['full_text']
                    elif key == 'indices':
                        start_index = value[0]
                        end_index = value[1]

                query = '''
              INSERT INTO entities (tweet_id, type, value, start_index,end_index)
                VALUES
                (?,?,?,?,?);
              '''
                c.execute(query,(tweet_id,type,type_value,start_index,end_index))  

conn.commit()
with conn:
  c.execute("SELECT * FROM entities")
  print(c.fetchall())

这就是我返回的内容:

[(1, 1408411651238371337, 'text', "#Hello World, 0, 19), (2, 1408411651238371337, 'url', 'www.co/DtjRrIzPTK', 211, 234).....

然而,这是错误的。我应该期望它是:

[(1, 1408411651238371337, 'Hashtags', "#Hello World, 0, 19), (2, 1408411651238371337, 'url', 'www.co/DtjRrIzPTK', 211, 234).....

标签: pythonjsonsqlitedictionarykey-value

解决方案


推荐阅读