-2

What code can I write to read python data from a json file I save and then convert it into a list?

Here is some sample code:

def read_json_file(filename):
    """
    reads from a json file and saves the result in a list named data
    """
    with open(filename, 'r') as fp:
        
        
    # INSERT THE MISSING PIECE OF CODE HERE
    
       
        data = json.loads(content)
    return data    
AMC
  • 2,642
  • 7
  • 13
  • 35
gurme har
  • 27
  • 3

2 Answers2

2

To import a json file, I recommend using the json libary. In your example, you would first need to import it.

import json

Then you can use

with open('filename.json', 'r') as fp:
    data = json.load(fp)

to get the data. Note that load is different from 'loads' (https://docs.python.org/2/library/json.html). You just need to change 'content' to 'fp' since that is how you referred to your file.

Note that this code stores returns the json as a dict, not as a list, which is different than what you are asking about, but probably what you want to use not knowing more about what you are trying to do.

eirenikos
  • 2,296
  • 25
  • 25
Teunis
  • 21
  • 4
0

You can basically use the builtin json module. Full documentation here : https://docs.python.org/3/library/json.html

To get a json string from object (any data like list, dict, etc...), use :

    import json

    json_str = json.dumps(my_data)  # Get json string representation of my_data
    fp.write(json_str)              # Write json_str string to file fp

Once you wrote your file you can read the json string from file with :

    json_str = fp.read()

And finally turn to a python object :

    import json

    my_data = json.loads(json_str)
AlexTorx
  • 753
  • 4
  • 9