0

Hopefully this isn't a duplicate post. I have read through the numerous others regarding this kind of issue, but have had no success.

I want to parse the below JSON to Python, to print the current price of the stock. I have tried this using the below code:

from googlefinance import getQuotes
import json

stock = json.loads(getQuotes('AAPL'))
print(stock['LastTradePrice'])

However, this gives the below error...

error

I have tried also the below code:

from googlefinance import getQuotes
import json

print(json.dumps(getQuotes('AAPL'), indent=2))

Which successfully gives the following output

[
  {
    "Index": "NASDAQ",
    "LastTradeWithCurrency": "129.09",
    "LastTradeDateTime": "2015-03-02T16:04:29Z",
    "LastTradePrice": "129.09",
    "Yield": "1.46",
    "LastTradeTime": "4:04PM EST",
    "LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
    "Dividend": "0.47",
    "StockSymbol": "AAPL",
    "ID": "22144"
  }
]

However, I just want to fetch the price from this and parse it through to a Python program. Why am I unable to do this? I have a feeling that it is because of the square brackets surrounding the json, but am unsure.

7
  • What about print(stock[0]['LastTradePrice'])? It is a list after all, with one element. Commented Jan 25, 2017 at 0:56
  • Apparently, qetQuotes deals with the json deserializing already, and is returning a Python object. Why would you dumps it? Commented Jan 25, 2017 at 0:58
  • How would I fetch it as a python object? Treat it like an accociative array? Commented Jan 25, 2017 at 0:59
  • It already returns a Python object. It is a list of dicts. Commented Jan 25, 2017 at 1:00
  • stock = getQuotes('AAPL'); print(stock[0]['LastTradePrice']) # 119.97 Commented Jan 25, 2017 at 1:00

1 Answer 1

3

It is not necessary to deserialize the data since it returns an list of dictionaries.

from googlefinance import getQuotes
data = getQuotes('AAPL')

print(data[0]['LastTradePrice'])

Output:

119.97
Sign up to request clarification or add additional context in comments.

1 Comment

A list. It returns a list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.