import json
j1 = '{"ip": "8.8.8.8"}'
d1 = json.loads(j1)
print(d1)
print(type(d1))
print(d1['ip'])
# 여러줄을 복사할 경우 '''''' 을 사용
j2 = '''{
"Accept-Language": "en-US,en;q=0.8",
"Host": "headers.jsontest.com",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}'''
#j2를 해석해서 값(value)만 출력해 보세요.
d2 = json.loads(j2)
print(d2)
print(type(d2))
for key in d2.keys():
print(d2[key])
for k, v in d2.items():
print(k, v)
for k in d2: # 딕셔너리를 직접 for문에 사용하면 key 값 반환
print(k)
print('-'*50)
# 파일 쓰기
def write_file(data):
f = open('Data/json_file.txt', 'w', encoding='utf-8')
for v, k in data.items():
f.write(v)
f.write(': ')
f.write(k)
f.write('\n')
f.close()
# loads : string --> object
# dumps : object --> string
j3 = json.dumps(d2)
print(j3)
print(type(j3))
write_file(d2)