gpt4 book ai didi

python - 使用python迭代json数据

转载 作者:行者123 更新时间:2023-12-01 03:22:31 24 4
gpt4 key购买 nike

我已经在这段代码上工作了几个小时,尝试了一些方法来迭代提供的 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

最佳答案

您收到 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))

关于python - 使用python迭代json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com