[python] JSON πŸ” λ”•μ…”λ„ˆλ¦¬ loads, dumps

RobinΒ·2022λ…„ 9μ›” 21일

Python

λͺ©λ‘ 보기
10/11

loads(): JSON ν˜•νƒœμ˜ λ¬Έμžμ—΄μ„ λ”•μ…”λ„ˆλ¦¬λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€. μ΄λ•Œ λ”•μ…”λ„ˆλ¦¬μ˜ λͺ¨λ“  μ›μ†ŒλŠ” λ¬Έμžμ—΄ νƒ€μž…μœΌλ‘œ μ„€μ •λ©λ‹ˆλ‹€.

dumps(): λ”•μ…”λ„ˆλ¦¬λ₯Ό JSON ν˜•νƒœμ˜ λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.

# json νŒ¨ν‚€μ§€λ₯Ό μž„ν¬νŠΈν•©λ‹ˆλ‹€.
import json



#JSON νŒŒμΌμ„ 읽고 λ¬Έμžμ—΄μ„ λ”•μ…”λ„ˆλ¦¬λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.
def create_dict(filename):
    with open(filename) as file:
        json_string = file.read()   #μ „μ²΄νŒŒμΌμ„ μ½μ–΄μ˜¨λ‹€
        new_dict = json.loads(json_string)
        return new_dict



#λ”•μ…”λ„ˆλ¦¬λ₯Ό JSON ν˜•νƒœμ˜ λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.
def create_json(dictionary, filename):
    with open(filename, 'w') as file: 		#"w" writeλͺ¨λ“œλ‘œ κ°€μ Έμ˜¨λ‹€
        json_string = json.dumps(dictionary)
        file.write(json_string)
        
        
        
# κ²°κ³Όλ₯Ό ν™•μΈν•΄λ΄…λ‹ˆλ‹€.
src = 'netflix.json'
dst = 'new_netflix.json'

netflix_dict = create_dict(src)				πŸ‘ˆ
print('μ›λž˜ 데이터: ' + str(netflix_dict))

netflix_dict['Dark Knight'] = 39217
create_json(netflix_dict, dst)				πŸ‘ˆ
updated_dict = create_dict(dst)				πŸ‘ˆ
print('μˆ˜μ •λœ 데이터: ' + str(updated_dict))

# μ›λž˜ 데이터: {'Iron Man': 31928, 'Iron Man 2': 15293, 'Dark Knight': 42107, 'Man in Black': 20113}
# μˆ˜μ •λœ 데이터: {'Iron Man': 31928, 'Iron Man 2': 15293, 'Dark Knight': 39217, 'Man in Black': 20113}
profile
Always testing, sometimes dog walking

0개의 λŒ“κΈ€