'Error when reading yahoofinancials JSON: Unexpected character found when decoding 'NaN'

I am trying to read a json, which I get from the python package 'yahoofinancials' (it pulls the data from Yahoo Finance):

import numpy as np
import pandas as pd
from yahoofinancials import YahooFinancials

yahoo_financials = YahooFinancials(ticker)
cash_statements = yahoo_financials.get_financial_stmts('annual', 'income')
cash_statements
pd.read_json(str(cash_statements).replace("'", '"'), orient='records')

However I get the error: Unexpected character found when decoding 'NaN'



Solution 1:[1]

Check whether the file is available or the file name is correct because I got the same error while reading a .json file that was not in that folder and located somewhere else.

Solution 2:[2]

The problem is this command: str(cash_statements).replace("'", '"').

You tried to "convert" from a python dictionary to a json string, by replacing single with double quotes, which does not properly work.

Use the json.dump(cash_statements) function for converting your dictionary object into a json string.

Updated Code:

import numpy as np
import pandas as pd
from yahoofinancials import YahooFinancials

# ADJUSTMENT 1 - import json
import json


# just some sample data for testing
ticker = ['AAPL', 'MSFT', 'INTC']

yahoo_financials = YahooFinancials(ticker)
cash_statements = yahoo_financials.get_financial_stmts('annual', 'income')

# ADJUSTMENT 2 - dict to json
cash_statements_json = json.dumps(cash_statements)
pd.read_json(cash_statements_json, orient='records')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anitya Gangurde
Solution 2 sergej