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

如何用Python调整JSON文件结构并添加对象标题

多API数据合并为结构化JSON的解决方案

问题说明

需要从两个不同API接口提取数据,生成以"AAPL"和"MSFT"为键、对应数据用数组包裹的结构化JSON文件。当前代码会生成两个独立的JSON对象,不符合预期格式。

原代码

import requests
import json

headers = {
    'accept-language': 'en-US,en;q=0.9',
    'origin': 'https://www.nasdaq.com/',
    'referer': 'https://www.nasdaq.com/',
    'accept': 'application/json, text/plain, */*',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}

dataAAPL = requests.get('https://api.nasdaq.com/api/company/AAPL/insider-trades?limit=15&type=ALL&sortColumn=lastDate&sortOrder=DESC', 
headers=headers).json()['data']['numberOfSharesTraded']['rows'][3]

dataMSFT = requests.get('https://api.nasdaq.com/api/company/MSFT/insider-trades?limit=15&type=ALL&sortColumn=lastDate&sortOrder=DESC', 
headers=headers).json()['data']['numberOfSharesTraded']['rows'][3]

with open('AAPL_insider_piechart.json', 'w') as f:
    json.dump(dataAAPL, f, indent=4)
    json.dump(dataMSFT, f, indent=4)

当前输出JSON

{
    "insiderTrade": "Net Activity",
    "months3": "(1,317,881)",
    "months12": "(1,986,819)"
}
{
    "insiderTrade": "Net Activity",
    "months3": "185,451",
    "months12": "31,944"
}

期望输出JSON

{
    "AAPL":[
        {
            "insiderTrade": "Net Activity",
            "months3": "(1,317,881)",
            "months12": "(1,986,819)"
        }
    ],
    
    "MSFT":[
        {
            "insiderTrade": "Net Activity",
            "months3": "185,451",
            "months12": "31,944"
        }
    ]
}

修改后的代码

import requests
import json

headers = {
    'accept-language': 'en-US,en;q=0.9',
    'origin': 'https://www.nasdaq.com/',
    'referer': 'https://www.nasdaq.com/',
    'accept': 'application/json, text/plain, */*',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}

# 提取两个接口的数据
dataAAPL = requests.get('https://api.nasdaq.com/api/company/AAPL/insider-trades?limit=15&type=ALL&sortColumn=lastDate&sortOrder=DESC', 
headers=headers).json()['data']['numberOfSharesTraded']['rows'][3]

dataMSFT = requests.get('https://api.nasdaq.com/api/company/MSFT/insider-trades?limit=15&type=ALL&sortColumn=lastDate&sortOrder=DESC', 
headers=headers).json()['data']['numberOfSharesTraded']['rows'][3]

# 构建符合预期的结构化字典
structured_data = {
    "AAPL": [dataAAPL],
    "MSFT": [dataMSFT]
}

# 写入JSON文件
with open('AAPL_insider_piechart.json', 'w') as f:
    json.dump(structured_data, f, indent=4)

修改说明

  1. 新增structured_data字典,以"AAPL"和"MSFT"为键,对应的值是将单个数据对象包裹在数组中,匹配期望的结构。
  2. 替换原代码中两次json.dump的操作,改为一次性将整个结构化字典写入文件,保证输出是一个合法的JSON对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:41:59