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

Python从JSON字符串取值存变量报错:TypeError: string indices must be integers

问题:从JSON字符串中取值时遇到TypeError错误?

我有一个file1.py文件,其中包含如下JSON格式的字符串数据:

data = '{"env":"production","user_id":"8xxxx0-f1xx-xxx6-bxxx-0a1xf6dxxxx","c_id":"ca0cad8xxxxe68962810d8axxxxb6a"}'

我尝试从file1.py中获取值并赋值给本地变量,代码如下:

import file1
import json

json_data = file1.data

env = json_data["env"]
user_id = json_data["user_id"]
channel_id = json_data["c_id"]

但我总是遇到错误:

TypeError: string indices must be integers

我搜索了很多类似错误的解决方案,但都无法解决我的问题。请问我哪里出错了?


解答

你核心的问题在于:file1.data是字符串类型,不是已经解析完成的JSON字典。直接对字符串使用["env"]这种键索引的方式,Python会默认你想取字符串的某个位置(需要整数索引),所以才抛出string indices must be integers的错误。

修正方法很简单,用json.loads()把JSON格式的字符串解析成Python字典,之后再用键取值即可:

import file1
import json

# 将JSON字符串解析为可直接用键访问的字典
json_data = json.loads(file1.data)

env = json_data["env"]
user_id = json_data["user_id"]
channel_id = json_data["c_id"]

这样就能正常获取到对应的值了。


内容的提问来源于stack exchange,提问作者sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:05:05