1. 程式人生 > >json解析與類別統計

json解析與類別統計

json檔案儲存
程式碼1:

# encoding: utf-8
import json

data = {

        'roles':
            [
                {'role':'monster','type':'pig','life':50},
                {'role':'hero','type':'關羽','life':80}
            ]


        }
# dumps把資料型別轉換成字串 dump把資料型別轉換成字串並存儲在檔案中
# d = json.dumps(data)
# print d
# d = json.dump(data,'exam3.json') # 這樣的語法會出錯 f = open('exam3.json','w') d = j

程式碼2:

import json
import datetime
import getpass
import time
import os


class CocoJsonWriter:
    def __init__(
            self,
            foldername,
            filename,
            imgSize,
            databaseSrc=
'Unknown', localImgPath=None, shape_type=None): self.foldername = foldername self.filename = filename self.databaseSrc = databaseSrc self.imgSize = imgSize self.boxlist = [] self.dict_list = [] self.localImgPath = localImgPath self.
shape_type = shape_type def addPolygon(self, name, instance_id): polygon = {} bpoint = [] # for point in shape: # b = list(point) # bpoint.append(b) # # bpoint[i] = list(point) # # i = i + 1 # polygon['polygon'] = bpoint polygon['label'] = name # polygon['point_num'] = str(len(shape)) polygon['id'] = instance_id polygon['deleted'] = 0 polygon['draw'] = True polygon['shape_type'] = self.shape_type polygon['verified'] = 0 user = getpass.getuser() polygon['user'] = user date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) polygon['date'] = date # self.boxlist.append(polygon) # dic=dict(label=cls_name,id=idx,date=nowTime,deleted=0,draw=True,user="None",verified=0,polygon=bpoint self.dict_list.append(polygon) def save(self, targetFile=None): # output_namej = os.path.basename(im_name).strip('.jpg') + '_gtFine_polygons' + '.json' # targetFile = os.path.join(json_dir, '{}'.format(output_namej)) djson = {"filename": self.filename, "imgHeight": self.imgSize[0], "imgWidth": self.imgSize[1], "depth": self.imgSize[2], "objects": self.dict_list } with open(targetFile, "w") as f: json.dump(djson, f, sort_keys=True, indent=4) print("%s saved." % targetFile) JsonWriter = CocoJsonWriter(foldername = '111',filename = '222',imgSize=[0,1,2],databaseSrc='Unknown') JsonWriter.addPolygon(name='333', instance_id=0) JsonWriter.save('exam.json')

json檔案解析

# -*- coding: utf-8 -*-
# 將 json格式的 class進行統一標籤
# 可以直接批量讀取json檔案,並修改內容
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import json
import os
import scipy.misc
import sys
path = ""
files = os.listdir(path)
label_list = []
total_num=0
for json_file in files:

    if json_file.endswith('.json'):
        total_num += 1
        json_path= os.path.join(path, json_file)
        print(json_path)
        json_ann = json.load(open(json_path))

        objects = json_ann['objects']
        for item in objects:
            # 列印 label
            # print (item['label'])
            label_list.append(item['label'])
print(label_list)
category = set(label_list)  # myset是另外一個列表,裡面的內容是mylist裡面的無重複 項

# readme_path =
# with open(path+'readme.txt','w') as f:
with open(os.path.join(path, 'readme'), 'w') as f:
    '''
    儲存資訊
    '''
    f.write('總json檔案數量 = %d'% total_num)
    f.write('\n類別數 = %s' % category)
    for label in category:
        print("the %s has found %d" % (label, label_list.count(label)))
        f.write("\nthe %s has found %d" % (label, label_list.count(label)))