【问题标题】:Parse json file using python使用python解析json文件
【发布时间】:2023-04-02 06:37:01
【问题描述】:

我有一个 .json 文件,前几行是:

{
    "global_id": "HICO_train2015_00000001",
    "hois": [
        {
            "connections": [
                [
                    0,
                    0
                ]
            ],
            "human_bboxes": [
                [
                    207,
                    32,
                    426,
                    299
                ]
            ],
            "id": "153",
            "invis": 0,
            "object_bboxes": [
                [
                    58,
                    97,
                    571,
                    404
                ]
            ]
        },

我想打印human_bboxes。 id 和 object_bboxes。

我试过这段代码:

    import json
     
    # Opening JSON file
    f = open('anno_list.json',)
     
    # returns JSON object as
    # a dictionary
    data = json.load(f)
     
    # Iterating through the json
    # list
    s=data[0]
    for i in s:
     print(i[1])
     
    # Closing file
    f.close()

但是,它给了我这个输出:

l

o

m

m

【问题讨论】:

  • 你检查过我更新的答案吗?

标签: python json parsing


【解决方案1】:

Behdad Abdollahi Moghadam 的答案将正确打印答案,但仅限于一组 bbox 和 id。下面的答案还有一个 for 循环,它解析整个文件并将所有人类和对象 bbox 和 id 打印到一个文件中。

import json
 
# Opening JSON file
f = open('anno_list.json',)
 
# returns JSON object as
# a dictionary
data = json.load(f)
 
f1 = open("file1.txt", "w")
for annotation in data:
    f1.write("==============\n")
    f1.write(annotation["global_id"])
    for hois in annotation["hois"]:
        f1.write("\n")
        f1.write("---")
        f1.write("\n")
        f1.write(hois["id"])
        f1.write("\n")
        f1.write(str(hois["human_bboxes"]))
        f1.write("\n")
        f1.write(str(hois["object_bboxes"]))
        f1.write("\n")
 
# Closing file
f.close()
f1.close()

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

这样做:

import json
# Opening JSON file
f = open('anno_list.json',)

# returns JSON object as
# a dictionary
data = json.load(f)
     
# Iterating through the json
# list
s=data[0]

# Do This:
hois_data = s["hois"][0]
print("human_bboxes",hois_data["human_bboxes"])
print("id",hois_data["id"])
print("object_bboxes",hois_data["object_bboxes"])
   
# Closing file
f.close()

【讨论】:

  • 我收到此错误:文件“load_json.py”,第 14 行,在 print("human_bboxes",s["human_bboxes"]) KeyError: 'human_bboxes'
  • 我已经更新了我的答案,请查看@usr18
  • 谢谢!这适用于第一组。我还想为整个文件打印出来。抱歉,如果我没有说清楚。
猜你喜欢
  • 2015-12-25
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
相关资源
最近更新 更多