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
相关产品推荐
相关产品推荐

