You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ast.literal_eval()时返回TextIOWrapper而非字符串的问题求助

Fix: ast.literal_eval() Returns TextIOWrapper Instead of Dictionary

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:55:33