简体   繁体   中英

Passing a json file to a method in Python

I have a json file on my computer that I need to pass to the following function:

def read_json(file):
    try:
        logging.debug('Reading from input')
        return read_json_from_string(json.load(file))
    finally:
        logging.debug('Done reading')

How can I move a file from my computer to a method in python? I have tried the following:

file = os.path.abspath('theFile.json')

Then attempting to run the method as

read_json(file)

But I get the following error:

TypeError: expected file

I also tried:

file = open('theFile.json', 'r')

But I always get an error related to the 'file' not being a file.

json.load takes a file-like object, and you're passing it a str containing the path. Try this instead:

path = os.path.abspath('theFile.json')
with open(path) as f:
    read_json(f)

Note that json.load returns a dictionary, not a string. Also, the finally: is executed even if an exception is raised in the try: , so you'll always log "Done reading", even if an error occurred and the read was aborted.

=====UPDATED=====

Now includes an example of calling the function


Try something like:

import logging
import json

def read_json(file):
    try:
        print('Reading from input')
        with open(file, 'r') as f:
            return json.load(f)
    finally:
        print('Done reading')

return_dict = read_json("my_file.json")
print return_dict

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM