Python无法解析json密钥

时间:2017-07-12 17:06:54

标签: python json

我有以下json(为了简单起见,我已经删除了大量数据):

{u'_links': [{u'uri': u'http://url/polling/v1/c1b1a360-1c69-49e0-9114-f02e3697e3ea', u'rel': u'header', u'methods': [u'GET', u'POST', u'PUT', u'OPTIONS']}, {u'uri': u'http://url/polling/v1/c1b1a360-1c69-49e0-9114-f02e3697e3ea/stores', u'rel': u'self', u'methods': [u'GET', u'PUT', u'POST', u'DELETE', u'OPTIONS']}], u'data': [{u'status': u'C2001', u'stackTrace': None, u'receivedIdx': 53713, u'description': u'Staged', u'timeChanged': u'2017-07-12T07:00:11.949-0400', u'storeNbr': u'1280', u'_links': [{u'uri': u'http://url.com/polling/v1/c1b1a360-1c69-49e0-9114-f02e3697e3ea/stores/1280', u'rel': u'self', u'methods': [u'GET', u'POST', u'DELETE', u'OPTIONS']}

我试图获得" timeChanged"和"描述"其中的字段。

data = json.loads(result.read())
for status in data:
  print "[",status['timeChanged'],"]", status['description']

结果:

  

TypeError:字符串索引必须是整数

我做错了什么?

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

让我们说<?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3"; $result = $mysqli->query($query); // to make sure there is something in the result set if ( $result->num_rows() > 0 ) { $row = $result->fetch_array() do { echo $row["Name"]; } while($row = $result->fetch_array()) } ?> 给你以下的词典:

data = json.loads(result.read())

当您迭代这样的字典时会发生什么?

{"foo": "bar", "baz": 3}

你明白了:

for x in data:
    print x

for循环遍历字典的键。因此,当您尝试使用字符串上的字符串进行子索引时,您的foo baz 。你想要这样的东西:

TypeError
好吧,也许吧。我对你的示例数据感到困惑,但你现在应该理解这个原则。

答案 1 :(得分:0)

我需要从“data”键获取值,然后从该数据键打印“field”。在这种情况下

for x in data["data"]:
   print x['timeChanged', x['description']