转载自https://www.cnpython.com/qa/1318923

目录

错误描述

当使用res.json["data"]却得到TypeError: 'method' object is not subscriptable

错误原因

当json中的key没有用双引号包裹,例如{abc:"1:2:3:4", efg:"5:6:7:8", "hij":"foo"},内置的json模块无法处理,会报错。

解决方案

方案一:正则替换修复

import re
jtxt_bad ='{abc:"1:2:3:4", efg:"5:6:7:8", "hij":"foo", klm:"bar"\n}'
jtxt = re.sub(r'\b([a-zA-Z]+):("[^"]+"[,\n}])', r'"\1":\2', jtxt_bad)
print(f'Original: {jtxt_bad}\nRepaired: {jtxt}')

输出为

Original: {abc:"1:2:3:4", efg:"5:6:7:8", "hij":"foo", klm:"bar"
}
Repaired: {"abc":"1:2:3:4", "efg":"5:6:7:8", "hij":"foo", "klm":"bar"
}

方案二:工具库

import dirtyjson

d = dirtyjson.loads('{address:"1600:3050:rf02:hf64:h000:0000:345e:d321"}')

print( d['address'] )

d = dirtyjson.loads('{abc:"1:2:3:4", efg:"5:6:7:8", "hij":"foo"}')

print( d['abc'] )

它创建AttributedDict,因此可能需要dict()来创建普通字典

d = dirtyjson.loads('{abc:"1:2:3:4", efg:"5:6:7:8", "hij":"foo"}')

print( d )

print( dict(d) )

结果:

AttributedDict([('abc', '1:2:3:4'), ('efg', '5:6:7:8'), ('hij', 'foo')])

{'abc': '1:2:3:4', 'efg': '5:6:7:8', 'hij': 'foo'}