skip to Main Content

I’m Trying to get the "5. adjusted close" data from this json file for each of the time periods.

{
    "Meta Data": {
        "1. Information": "Monthly Adjusted Prices and Volumes",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2024-02-22",
        "4. Time Zone": "US/Eastern"
    },
    "Monthly Adjusted Time Series": {
        "2024-02-22": {
            "1. open": "183.6300",
            "2. high": "188.9500",
            "3. low": "178.7500",
            "4. close": "184.2100",
            "5. adjusted close": "184.2100",
            "6. volume": "67308725",
            "7. dividend amount": "1.6600"
        },
        "2024-01-31": {
            "1. open": "162.8300",
            "2. high": "196.9000",
            "3. low": "157.8850",
            "4. close": "183.6600",
            "5. adjusted close": "182.0211",
            "6. volume": "128121557",
            "7. dividend amount": "0.0000"
        }}}

I get the json file and store it as "data". I was hoping this would work but doesn’t

r = requests.get(url2)
data = r.json()

for entry in data["Monthly Adjusted Time Series"]:
    print(entry["5. adjusted close"])

3

Answers


  1. Did you want to loop over the values? When you loop over a dict, it only gives the keys

    >>> for _, entry in data["Monthly Adjusted Time Series"].items():
    ...     print(entry["5. adjusted close"])
    ...
    184.2100
    182.0211
    
    Login or Signup to reply.
  2. You say you have a JSON file. In which case:

    import json
    
    with open("foo.json") as data:
        d = json.load(data)
        for v in d["Monthly Adjusted Time Series"].values():
            print(v.get("5. adjusted close"))
    
    Login or Signup to reply.
  3. import json

    json_string = ”'{
    "Meta Data": {
    "1. Information": "Monthly Adjusted Prices and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2024-02-22",
    "4. Time Zone": "US/Eastern"
    },
    "Monthly Adjusted Time Series": {
    "2024-02-22": {
    "1. open": "183.6300",
    "2. high": "188.9500",
    "3. low": "178.7500",
    "4. close": "184.2100",
    "5. adjusted close": "184.2100",
    "6. volume": "67308725",
    "7. dividend amount": "1.6600"
    },
    "2024-01-31": {
    "1. open": "162.8300",
    "2. high": "196.9000",
    "3. low": "157.8850",
    "4. close": "183.6600",
    "5. adjusted close": "182.0211",
    "6. volume": "128121557",
    "7. dividend amount": "0.0000"
    }
    }
    }”’

    data = json.loads(json_string)
    monthly_adj_close = {date: data[‘Monthly Adjusted Time Series’][date][‘5. adjusted close’] for date in data[‘Monthly Adjusted Time Series’]}
    print(monthly_adj_close)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search