如何选取JSON中名为contents的数组并转换为Pandas DataFrame?
解决方法
你的数据是JSON格式,不需要用BeautifulSoup(它是用来解析HTML/XML的),直接用json模块解析后提取contents数组,再转成DataFrame即可,步骤如下:
- 导入必要模块:导入
json和pandas(无需BeautifulSoup) - 解析JSON字符串:将JSON字符串转换为Python字典
- 提取目标数组:从字典中取出
contents对应的数组 - 转换为DataFrame:用
pandas.DataFrame()将数组转为DataFrame
完整代码示例:
import json import pandas as pd # 你的JSON字符串 html_sample3 = """{ "orderID": 12345, "shopperName": "John Smith", "shopperEmail": "johnsmith@example.com", "contents": [ { "productID": 34, "productName": "SuperWidget", "quantity": 1 }, { "productID": 56, "productName": "WonderWidget", "quantity": 3 } ], "orderCompleted": true }""" # 解析JSON为字典 order_data = json.loads(html_sample3) # 提取contents数组并转为DataFrame contents_df = pd.DataFrame(order_data["contents"]) # 查看结果 print(contents_df)
运行后得到的DataFrame样式如下:
| productID | productName | quantity |
|---|---|---|
| 34 | SuperWidget | 1 |
| 56 | WonderWidget | 3 |
内容的提问来源于stack exchange,提问作者Owen
相关产品推荐
相关产品推荐

