使用ast.literal_eval()时返回TextIOWrapper而非字符串的问题求助
Hey there! Let's break down why you're hitting this issue and how to fix it quickly.
The core problem here is that you're passing a file object (the TextIOWrapper you're seeing) directly to ast.literal_eval(), instead of first reading the string content inside the file. That's why the function isn't parsing the data into a dictionary like you expect.
Let's fix this step by step:
1. Correct way to use ast.literal_eval() with a file
First, you need to read the file's content into a string, then pass that string to ast.literal_eval():
import ast # Open the file, read its content as a string, then parse with open("your_json_file.json", "r") as f: file_content = f.read() # This gets the actual string from the file parsed_dict = ast.literal_eval(file_content) print(type(parsed_dict)) # Now this will output <class 'dict'> print(parsed_dict["productName"]) # You can access keys normally now
2. Even better: Use the json module (since your data is valid JSON)
Since your data is already in JSON format, using Python's built-in json module is more appropriate than ast.literal_eval()—it's purpose-built for JSON parsing and handles edge cases better:
import json # Option 1: Parse directly from the file with open("your_json_file.json", "r") as f: parsed_dict = json.load(f) # json.load() reads the file and parses it in one step # Option 2: If you already have the string from the API (no need to write to file first!) api_response_str = '{"productId":1200,"productName":"Mox Sapphire",...}' # Your API string parsed_dict = json.loads(api_response_str) print(type(parsed_dict)) # Outputs <class 'dict'>
A quick tip: When you get JSON data from an API, you don't even need to write it to a file first—you can parse the response string directly with json.loads() (or use response.json() if you're using requests, which parses it automatically!).
内容的提问来源于stack exchange,提问作者juju

