can't read json file with python. getting type error: json object is 'TextIOWrapper'

前端 未结 3 1459
不知归路
不知归路 2020-12-03 11:31

I\'m trying to read from a json file.

This is how I created the file:

import requests
import json
import time
from pprint import pprint

BASE_URL = \         


        
相关标签:
3条回答
  • 2020-12-03 11:41

    Use json.load() (without 's') instead of json.loads()

    PS You will be using json.load() when loading from file. And json.loads() when working with string :)

    0 讨论(0)
  • 2020-12-03 11:43

    3 ways to load a json file:

    import json
    import ast
    with open(file_path) as file:
        data1 = json.load(file)
        data2 = json.loads(file.read())  
        data3 = ast.literal_eval(file.read())
    

    You should use json.load whenever possible, but sometimes the JSON file is not strictly in the correct format (e.g. single quotes instead of double quotes). A solution is to use ast.literal_eval().

    0 讨论(0)
  • 2020-12-03 11:57

    json.load() is for loading a file. json.loads() works with strings.

    0 讨论(0)
提交回复
热议问题