본문 바로가기
Data/Data Engineering

JSONPath 라이브러리와JSON파싱(load/dump/loads/dumps)

by 카프리썬 2021. 6. 26.
728x90

 

어디서 알게 되었나?

프로젝트를 진행하다가 jsonpath라는 라이브러리를 써야해서 추가로 알아보았따. 

s3로 datalake를 구현하면서 계층구조를 가지고 있는 api데이터를 jsonpath를 사용해서 변형했다. 

 

예를 들면 이런식으로 사용했다. 그땐 이렇구나~라고 넘어갔지만 이제 본격적으로 알아보자. 

      for track in raw['tracks']: # i는 하나의 트랙
            #s3에 넣기 위한 flat한 데이터로 변환
            top_track = {}
            for k, v in top_track_keys.items():
                value = jsonpath.jsonpath(track, v)
                # 해당 위치에 데이터가 없으면 False를 리턴(bool type). 이럴 경우 다음 컬럼으로 넘어감
                if type(value) == bool:
                    continue
                top_track.update({k: value[0]}) #필드값이 []형태가 아니라, string으로 받기 위해 value[0]
                top_track.update({'artist_id': artist_id}) # key 값을 위해 아티스트 id도 넣어줌
            top_tracks.append(top_track)

JsonPath

JSON객체를 탐색하기 위한 표준화된 방법으로 JSON을 쉽게 처리할 수 있는 표현식을 제공한다 

 

구글링하며 찾은 jsonapath으 내용은 이것이다 >> java jayway jsonpath 

연산자,함수를 가지고 json데이터를 쉽게 가져오는 것 같은데 

내가 알고 싶은건 jsonpath.jsonpath에 해당하는 내용인데 다른부분같다..

우선보류..

 

유용한 사이트

표현식 테스트  http://jsonpath.herokuapp.com/

 

Jayway JsonPath evaluator

Goessner examle Twitter API Webapp 20k { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.

jsonpath.herokuapp.com


Json파싱하기

추가로 구글링하다가 알게 된 json파싱하는 방법 정리를 덧붙여본다.

key-value쌍으로 이루어진 json형식 

value에는 number,string,bool,arry,object,null이 들어갈 수 있다

loads() : json문자열을 python객체로 변환 

대부분 파일에 저장되어 있는 json문자열을 읽거나, http요청의 body를 읽을때 자주사용 

import json

json_string = '''{
    "id": 1,
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874"
    },
    "admin": false,
    "hobbies": null
}'''

json_object = json.loads(json_string)

assert json_object['id'] == 1
assert json_object['email'] == 'Sincere@april.biz'
assert json_object['address']['zipcode'] == '92998-3874'
assert json_object['admin'] is False
assert json_object['hobbies'] is None

dumps() : python객체를 json문자열로 반환 

print한 결과 json문자열로 반환했을떄 한줄로 나와서,  

json.dumps(object,indent=2) indent 옵션을 통해 그만큼 들여쓰기가 되어 json문자열로 변환한다 

import json

json_object = {
    "id": 1,
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874"
    },
    "admin": False,
    "hobbies": None
}

json_string1 = json.dumps(json_object)
print(json_string1)
#{"id": 1, "username": "Bret", "email": "Sincere@april.biz", "address": {"street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874"}, "admin": false, "hobbies": null}

json_string2 = json.dumps(json_object, indent=2)
print(json_string2)
#{
  "id": 1,
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874"
  },
  "admin": false,
  "hobbies": null
}

 

load() : JSON파일을 Python 객체로 불러오기 

대부분 with과 함꼐 씌여 .json파일을 읽어서 python 객체로 가져올때 쓰인다 

import json

with open('data.json') as f:
    json_object = json.load(f)

dump() : python 객체를 json파일로 저장하기 

python 객체를 json문자로 변환한 결과 바로 쓰고 싶을때 사용한다 

with open('data.json', 'w') as f:
    json_string = json.dump(json_object, f, indent=2)

 

정리 

loads() : json문자열을 python객체로 변환 

dumps() : python객체를 json문자열로 반환 

load() : JSON파일을 Python 객체로 불러오기 

dump() : python 객체를 json파일로 저장하기 

 

 

출처

https://www.daleseo.com/python-json/

 

[파이썬] json 모듈로 JSON 데이터 다루기

Engineering Blog by Dale Seo

www.daleseo.com

 

반응형