I'm trying to extract data from two different api endpoints and create a JSON file with said data. I wish to have titles for each object to distinguish the different data. My code is below:
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)
And this is the output JSON:
{
"insiderTrade": "Net Activity",
"months3": "(1,317,881)",
"months12": "(1,986,819)"
}
{
"insiderTrade": "Net Activity",
"months3": "185,451",
"months12": "31,944"
}
What I need, is for the JSON to look something like this:
{
"AAPL":[
{
"insiderTrade": "Net Activity",
"months3": "(1,317,881)",
"months12": "(1,986,819)"
}
],
"MSFT":[
{
"insiderTrade": "Net Activity",
"months3": "185,451",
"months12": "31,944"
}
]
}
CodePudding user response:
Just create a dictionary and place the two values in it before dumping it as JSON.
Solution
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)