Home > Software engineering >  Parse json file using python
Parse json file using python

Time:11-24

I have a .json file , the first few lines are :

{
    "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
                ]
            ]
        },

I want to print out human_bboxes. id and object_bboxes.

I tried this code:

    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()

But, it gave me this output:

l

o

m

m

CodePudding user response:

Do this:

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()

CodePudding user response:

The answer by Behdad Abdollahi Moghadam would print the answer correctly, but only for one set of bboxes and id. The below answer additionally has a for loop which parses the entire file and prints all the human and object bboxes and id into a file.

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()
  • Related