Search code examples
pythonalpha-vantage

How do I isolate a .json file?


I was trying to split some parts of a .json, to completely isolate parts of a .json file from an API I found.

This is trying to isolate the open share price of any stocks on the internet. I've consulted with Stack Overflow, but I think I may have made a mistake in my paraphrasing.

# example
import sys
import requests
import json
from ticker import *


def main():
    stock_ticker = input("Name the stock ticker?\n")
    time2 = int(input("How many minutes do you want to view history?\n"))

    #separate file to generate URL for API
    url =  webpage(stock_ticker, time2)
    response = requests.get(url)

    assert response.status_code == 200

    data = json.loads(response.text)
    open_share_price = data["Time Series (5min)"]["2019-11-01 16:00:00"]["1. open"]
    print(open_share_price)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Returns

136.800

I've been wanting to get open share prices from different time frames, not just 16 :00:00, and not just at 5 min intervals.

I'm not great at programming, so any help would be gratefully received. Sorry in advance for my conciseness errors

Edit: The link for the data. Sorry I didn't include it the first time around. https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=kmb&interval=5min&apikey=exampleapikey


Solution

  • If you have to more than one element then you should use for-loop

    import requests
    
    url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=kmb&interval=5min&apikey=exampleapikey'
    
    response = requests.get(url)
    data = response.json()
    
    for key, val in data["Time Series (5min)"].items():
        print(key, val["1. open"])
    

    If you want to keep it as JSON then create new directory to keep values and later save it in file.

    import requests
    import json
    
    url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=kmb&interval=5min&apikey=exampleapikey'
    
    response = requests.get(url)
    data = response.json()
    
    new_data = dict()
    
    for key, val in data["Time Series (5min)"].items():
        new_data[key] = val["1. open"]
    
    #print(new_data)    
    
    with open('new_data.json', 'w') as fp:
        fp.write(json.dumps(new_data))