使用 python 解析 json 文件
Parse json file using python
我有一个 .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
这样做:
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()
Behdad Abdollahi Moghadam 的答案会正确打印答案,但仅限于一组 bboxes 和 id。下面的答案还有一个 for 循环,它解析整个文件并将所有人类和物体 bboxes 和 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()
我有一个 .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
这样做:
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()
Behdad Abdollahi Moghadam 的答案会正确打印答案,但仅限于一组 bboxes 和 id。下面的答案还有一个 for 循环,它解析整个文件并将所有人类和物体 bboxes 和 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()