Search code examples
pythonjsonstringindices

Parse code within json (Python)


I have the following Code:

from googlefinance import getQuotes
import simplejson as json

print (json.dumps(getQuotes('FRA:BMW'), indent=2))
b=(json.dumps(getQuotes('FRA:BMW'), indent=2))
print(type(b))
a = json.loads((json.dumps(getQuotes('FRA:BMW'), indent=2)))
print(type(a))

This is what I get:

[
  {
    "LastTradePrice": "73.39",
    "LastTradeWithCurrency": "€73.39",
    "LastTradeDateTime": "2016-05-13T19:57:30Z",
    "LastTradeDateTimeLong": "May 13, 7:57PM GMT+2",
    "ID": "10224532",
    "Index": "FRA",
    "StockSymbol": "BMW",
    "LastTradeTime": "7:57PM GMT+2"
  }
]
<class 'str'>
<class 'list'>
[{'LastTradePrice': '73.39', 'LastTradeWithCurrency': '&#8364;73.39', 'LastTradeDateTimeLong': 'May 13, 7:57PM GMT+2', 'LastTradeDateTime': '2016-05-13T19:57:30Z', 'ID': '10224532', 'Index': 'FRA', 'StockSymbol': 'BMW', 'LastTradeTime': '7:57PM GMT+2'}]
test
Traceback (most recent call last):
  line 11, in <module>
    print((a)["Index"])

TypeError: list indices must be integers or slices, not str

As you see I am not able to print the "Index" Value (in that case:FRA) (last code line of the script) No idea how that could work.


Solution

  • You don't need the json module to read that data. It is already a Python dictionary. The error said you have to index the list that getQuotes returns. Since there is only one element, you can use [0]

    >>> from googlefinance import getQuotes
    >>> fra_bmw = getQuotes('FRA:BMW')
    >>> fra_bmw[0]["Index"]
    u'FRA'