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}