【问题标题】:Python how to parse out values in a json response objectPython如何解析json响应对象中的值
【发布时间】:2015-05-14 18:08:51
【问题描述】:

试图从 json 响应中提取数据。响应包含可能包含此问题的额外方括号?

if debug: print "add_context_object Request: " + repr(response.url)
if debug: print "add_context_object Response: " + repr(response.content)
result = json.loads(response.content)
print result
print "Starting parse..."
wrapper = result.get("RoutingObj" , result)

add_context_object回复:

'[[{"RoutingObj": {"serialVersionUID":1,"balance":30000.0,"delinquency":null,"routeType":"Platinum"}}]]'

json.loads 返回:

[[{u'RoutingObj': {u'delinquency': None, u'balance': 30000.0, u'routeType': u'Platinum', u'serialVersionUID': 1}}]]

代码错误表明它是一个列表:

wrapper = result.get("RoutingObj" , result)
AttributeError: 'list' object has no attribute 'get'

【问题讨论】:

  • 谢谢,还发现在初始设置结果时添加索引有效:'result = eval(response.content)[0][0]' 它可能不如下面的答案灵活,但我看不出 Web 服务会返回多个索引的原因。

标签: python json get


【解决方案1】:

您应该使用正则表达式从 [[ 和 ]] 之间获取 json,这些方括号导致 python 认为它是列表中的列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多