【问题标题】:Changing layout and adding titles to JSON file with python使用 python 更改布局并向 JSON 文件添加标题
【发布时间】:2022-11-27 20:37:05
【问题描述】:

我正在尝试从两个不同的 api 端点提取数据并使用所述数据创建一个 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"
        }
    ]
}

【问题讨论】:

    标签: python json api


    【解决方案1】:
    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:
         obj = {
                "AAPL": [dataAAPL],                               
                "MSFT": [dataMSFT]                            
        }
        json.dump(obj, f, indent=4)
    

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多