通过json数据与python进行交互

时间:2017-01-23 01:12:33

标签: python json

我一直在研究这段代码几个小时,尝试了一堆东西来迭代提供的json数据。可以弄清楚如何正确迭代这些嵌套列表和对象。

import json

data = """
{
 "tracks": "1",
 "timeline": {
"0.733251541": [
  {
    "id": 1,
    "bounds": {
      "Width": 0.5099463905313426,
      "Height": 0.2867199993133546,
      "Y": 0.4436400003433228,
      "X": 0.4876505160745349
    }
  }
],
"0.965": [
  {
    "id": 1,
    "bounds": {
      "Width": 0.4205311330135182,
      "Height": 0.2363199994340539,
      "Y": 0.2393400002829731,
      "X": 0.1593787633901481
    }
  }
],
"1.098224": [
  {
    "id": 1,
    "bounds": {
      "Width": 0.4568560813801344,
      "Height": 0.2564799993857742,
      "Y": 0.1992600003071129,
      "X": 0.1000513407532317
    }
  }
]
  },
"taggedTracks": {
"1": "dirk"
}
}
"""

json = json.loads(data)

for a in json["timeline"]:
    for b in a:
        for c in b["bounds"]:
            print a, c["Width"], c["Height"], c["Y"], c["X"]

有人可以指导我如何处理所提供的json数据吗?

我收到以下错误。

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: string indices must be integers

2 个答案:

答案 0 :(得分:2)

您正在获取TypeError,因为在“timeline”的每个值中,首先出现一个列表。您必须使用索引0获取该列表的第一个值。然后您可以解析其余的。

希望以下代码有所帮助:

import json

data = """
{
"tracks": "1",
"timeline": {
"0.733251541": [
{
    "id": 1,
    "bounds": {
    "Width": 0.5099463905313426,
    "Height": 0.2867199993133546,
    "Y": 0.4436400003433228,
    "X": 0.4876505160745349
    }
}
],
"0.965": [
{
    "id": 1,
    "bounds": {
    "Width": 0.4205311330135182,
    "Height": 0.2363199994340539,
    "Y": 0.2393400002829731,
    "X": 0.1593787633901481
    }
}
],
"1.098224": [
{
    "id": 1,
    "bounds": {
    "Width": 0.4568560813801344,
    "Height": 0.2564799993857742,
    "Y": 0.1992600003071129,
    "X": 0.1000513407532317
    }
}
]
},
"taggedTracks": {
"1": "dirk"
}
}
"""

test_json = json.loads(data)

for num, data in test_json["timeline"].iteritems():
    print(num+":")
    bounds = data[0]["bounds"]
    for bound, value in bounds.iteritems():
        print('\t'+bound+": "+str(value))

答案 1 :(得分:0)

首先,对变量使用名称json并不是一个好主意,因为这是模块的名称。我们改用j

无论如何,当你json.loads()时,你会得到一个dict。当您迭代for a in <dict>时,您将返回键列表(仅限)。您可以使用iteritems()迭代键和值,例如:

for k, a in j['timeline'].iteritems():
    for b in a:
        c = b['bounds']
        print k, c["Width"], c["Height"], c["Y"], c["X"]