취미삼아 배우는 프로그래밍

Generator를 사용해 다양한 깊이의 json 파싱 방법 본문

파이썬(장고)

Generator를 사용해 다양한 깊이의 json 파싱 방법

Nadure 2020. 5. 15. 06:23

예제 json 파일

student_file.json
0.05MB

 

PDF 페이지의 텍스트를 파싱하다 보면 아래처럼 엄청나고 다양한 깊이의 json을 맛보게 된다

원하는 값은 'text' 및 'bbox'에 들어간 좌표.

 

먼저 보면,

block이라는 키 안에 리스트 형식이 엄청 많이 들어가 있는데,

문제는 bbox가 엄청 많이 나오고, 추출하고자 하는 text가 있기도 하고 없기도 하다.

그냥 bbox만 있는경우가 허다하다.

 

이때는 어떤식으로 파싱을 하는게 좋을까?

 

답은 recursive generator를 이용해

차곡차곡 담는거다

stackoverflow.com/questions/52725568/how-to-yield-in-a-recursive-function-in-python

 

How to Yield in a recursive function in Python

So I have a dictionary: {'a': {'b': {'c': 'd', 'e': 'f'}}} I need to create a dictionary as follows: {'c':'d', 'e','f'} It can go deeper up to any level but I should always get the key value pa...

stackoverflow.com

 

# Json 파일을 열고,
with open('student_file.json', 'r') as st_json:
    st_python = json.load(st_json)


def recursive_generator_example(d):
    if ('text' in d):              # text가 d 안에 있으면
        yield d['text'], d['bbox'] # 원하는 값을 할당 받아라.
    for k in d: 				   # 아니면 그 안 쪽의 것을 까보는데,
        if isinstance(d[k], list): # 만약에 리스트면, 그 안쪽의 것들에 대해 또 넣어본다.
            for i in d[k]:
                if(type(i) != float):
                    for j in recursive_generator_example(i):
                        yield j
                        

result = list(recursive_generator_example(st_python))
print(result)

 

bbox 때문에 더럽게 보일 지 모르지만, 아주 클린하게 값이 나온다.

 

Comments