如何使用Python3解析JSON中字典列表内的内容
如何正确解析JSON中的features数据并提取字段内容
首先得先理清你的JSON结构——外层是一个带data键的对象,data对应的是一个数组,数组里的每一项都是包含features字典和user_id字段的用户条目。你之前的代码问题出在遍历层级没搞对,所以才只拿到了键名而不是实际值。
先看你的JSON结构示例(简化版):
{ "data": [ { "features": { "location": "West Springfield, MA", "geo_type": "User location", // 其他字段... }, "user_id": 2158092352 }, // 第二个用户条目... ] }
问题出在哪?
你原来的代码里,json_array是解析后的字典(不是数组!),直接遍历它会拿到data这个键;然后把json_array[item]也就是data数组的元素加到tweet_list后,用for features,user in tweet_list的写法,其实是在遍历每个条目字典的键,所以只会输出features和user_id这两个键名,而不是它们对应的值。
修正后的解析代码
下面是能正确提取所有字段的代码,我加了注释方便你理解:
import json # 用with语句处理文件,自动关闭更安全 with open('file.json', 'r') as input_file: # 解析JSON成Python字典 json_data = json.load(input_file) # 遍历data数组里的每一个用户条目 for user_entry in json_data['data']: # 直接提取features字典和user_id features_dict = user_entry['features'] user_id = user_entry['user_id'] # 从features字典里取出各个字段 location = features_dict['location'] geo_type = features_dict['geo_type'] screen_name = features_dict['screen_name'] primary_geo = features_dict['primary_geo'] feature_id = features_dict['id'] # 这个和外层user_id值一样,按需使用 tweets_count = features_dict['tweets'] name = features_dict['name'] # 先打印验证一下是否正确提取 print(f"用户ID: {user_id}") print(f"姓名: {name}") print(f"位置: {location}") print(f"地理类型: {geo_type}") print("---")
把数据传入数据库的示例
假设你用SQLite(其他数据库逻辑类似,只是连接和占位符有小区别),可以用参数化查询来插入数据,避免SQL注入风险:
import sqlite3 # 连接数据库(不存在则自动创建) conn = sqlite3.connect('user_tweets.db') cursor = conn.cursor() # 先创建用户表(如果还没创建) cursor.execute(''' CREATE TABLE IF NOT EXISTS user_profiles ( user_id INTEGER PRIMARY KEY, full_name TEXT, screen_name TEXT UNIQUE, location TEXT, geo_type TEXT, primary_geo TEXT, tweet_count INTEGER ) ''') # 遍历数据插入数据库 for user_entry in json_data['data']: features_dict = user_entry['features'] user_id = user_entry['user_id'] # 准备插入的参数,按表字段顺序排列 insert_values = ( user_id, features_dict['name'], features_dict['screen_name'], features_dict['location'], features_dict['geo_type'], features_dict['primary_geo'], features_dict['tweets'] ) # 用?作为占位符执行插入,避免SQL注入 cursor.execute(''' INSERT OR REPLACE INTO user_profiles (user_id, full_name, screen_name, location, geo_type, primary_geo, tweet_count) VALUES (?, ?, ?, ?, ?, ?, ?) ''', insert_values) # 提交更改并关闭连接 conn.commit() conn.close()
如果用MySQL或者PostgreSQL,只需要把连接部分换成对应的库(比如mysql-connector-python或psycopg2),占位符换成%s(MySQL)或%s/%()(PostgreSQL)即可。
内容的提问来源于stack exchange,提问作者Bonzay
相关产品推荐
相关产品推荐

