如何隔离 .json 文件?

How do I isolate a .json file?

我试图拆分 .json 的某些部分,以将 .json 文件的部分与我找到的 API 完全隔离。

这是试图隔离互联网上任何股票的公开股价。我咨询过 Stack Overflow,但我认为我的解释可能有误。

# 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

我一直想获得不同时间范围内的开盘价,而不仅仅是 16:00:00,也不仅仅是 5 分钟的时间间隔。

我不擅长编程,所以如果能提供任何帮助,我们将不胜感激。提前为我的简洁错误道歉

编辑:数据的 link。对不起,我第一次没有包括它。 https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=kmb&interval=5min&apikey=exampleapikey

如果你需要一个以上的元素,那么你应该使用 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"])

如果您想将其保留为 JSON,则创建新目录以保留值,然后将其保存在文件中。

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))