You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何选取JSON中名为contents的数组并转换为Pandas DataFrame?

解决方法

你的数据是JSON格式,不需要用BeautifulSoup(它是用来解析HTML/XML的),直接用json模块解析后提取contents数组,再转成DataFrame即可,步骤如下:

  1. 导入必要模块:导入json和pandas(无需BeautifulSoup)
  2. 解析JSON字符串:将JSON字符串转换为Python字典
  3. 提取目标数组:从字典中取出contents对应的数组
  4. 转换为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样式如下:

productIDproductNamequantity
34SuperWidget1
56WonderWidget3

内容的提问来源于stack exchange,提问作者Owen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:10:35