0

The problem that I am running into is that 'data' variable is not being set whenever I try to read in the json object. I only get an empty set. Below I have the code and the outputs.

import json

data = []

def add(name, amt):
  data.append({"ticker": name, "amount": amt})

def write():
  with open('portfolio.json', 'w') as file:
    json.dump(data, file)

def load():
  with open('portfolio.json', 'r') as file:
     data = json.load(file)

def main():
  choice = input("Do you want to add vals? (y/n): ")
  if choice == 'y':    
    add('btc', 43.2)
    add('xrp', 256.5)
    add('xmr', 655.3)
    print(data)
    write()

  if choice == 'n':
    load()
    print(data)

main()

Output 1:

Do you want to add vals? (y/n): y
[{'ticker': 'btc', 'amount': 43.2}, {'ticker': 'xrp', 'amount': 256.5}, {'ticker': 'xmr', 'amount': 655.3}]
Press any key to continue . . .

So now the file 'portfolio.json' contains the json object with all of the data, correct? So, now when I try to read that in, this is what I get:

Output 2:

Do you want to add vals? (y/n): n
[]
Press any key to continue . . .

As you can see, the data variable is just an empty set, and it is not taking in the data. However, if I were to go inside the load function and print out the data variable, I would get my value.

Sam Autrey
  • 121
  • 1
  • 4

1 Answers1

0

You need to add a return statement in your load function and store the result in data variable before printing it.

Ex:

def load():
  with open(filename, 'r') as file:
      return json.load(file)

def main():
  choice = input("Do you want to add vals? (y/n): ")
  if choice == 'y':    
    add('btc', 43.2)
    add('xrp', 256.5)
    add('xmr', 655.3)
    print(data)
    write()

  if choice == 'n':
    data = load()
    print(data)
Rakesh
  • 81,458
  • 17
  • 76
  • 113