Jun's Blog
간단한 기능 구현해보기(JSON) - (7) 본문
1. JSON 파일로부터 데이터 읽어오기
1.1 JSON 파일 생성하기
[
{
"name": "이연수",
"kor": "60.0",
"eng": "70.0",
"math": "80.0",
"hello": "여러분 안녕~~",
"gender": "F"
},
{
"name": "강민섭",
"kor": "65.0",
"eng": "75.0",
"math": "85.0",
"gender": "M"
}
]
1.2 JSON 파일의 내용을 읽어오기
filename = 'JsonTest.json'
myfile = open(file=filename, mode='rt', encoding='UTF-8')
mystring = myfile.read()
print(type(mystring))
myfile.close()
import json
jsonData = json.loads(mystring)
print(type(jsonData))
print(type(jsonData[0]))
print(jsonData)
for info in jsonData:
print(info)
<실행결과>
filename = 'JsonTest.json'
myfile = open(file=filename, mode='rt', encoding='UTF-8')
mystring = myfile.read()
# print(type(mystring))
myfile.close()
import json
jsonData = json.loads(mystring)
# print(type(jsonData))
# print(type(jsonData[0]))
# print(jsonData)
# 사람들의 정보를 tuple 형식으로 담고 있는 list
infoList = list()
for info in jsonData:
name = info['name']
kor = float(info['kor'])
eng = float(info['eng'])
math = float(info['math'])
total = kor + eng + math
if 'hello' in info.keys():
message = info['hello']
else:
message = ''
# end if
_gender = info['gender'].upper()
if _gender == 'M':
gender = '남자'
else:
gender = '여자'
# end if
mytuple = (name, kor, eng, math, total, message, gender)
infoList.append(mytuple)
# end for
print(infoList)
<실행결과>
2. Dict 데이터를 입력하여 JSON 파일로 생성하기
humanDict = {
'age' : 20,
'name' : '홍길동',
'hobby' : '독서',
'address' : {'city' : 'anyang', 'gu' : '동안구', 'zipcode' : '12345'}
}
print(type(humanDict))
print(humanDict)
import json
humanString = json.dumps(humanDict, ensure_ascii=False, indent= 4, sort_keys=True)
print(type(humanString))
print(humanString)
<실행결과>
humanDict = {
'age' : 20,
'name' : '홍길동',
'hobby' : '독서',
'address' : {'city' : 'anyang', 'gu' : '동안구', 'zipcode' : '12345'}
}
# print(type(humanDict))
# print(humanDict)
import json
humanString = json.dumps(humanDict, ensure_ascii=False, indent= 4, sort_keys=True)
# print(type(humanString))
# print(humanString)
humanJson = json.loads(humanString)
print(f'이름 : {humanJson["name"]}')
print(f'취미 : {humanJson["hobby"]}')
print(f'나이 : {humanJson["age"]}')
print(f'시도 : {humanJson["address"]["city"]}')
print(f'군구 : {humanJson["address"]["gu"]}')
print(f'우편번호 : {humanJson["address"]["zipcode"]}')
<실행결과>
'Python' 카테고리의 다른 글
Python관련 라이브러리 참고 사이트 정보 (0) | 2025.03.06 |
---|---|
간단한 기능 구현해보기(정규 표현식) - (8) (0) | 2025.03.06 |
간단한 기능 구현해보기(XML) - (6) (1) | 2025.03.06 |
간단한 기능 구현해보기(파일 입출력) - (5) (0) | 2025.03.05 |
간단한 기능 구현해보기(함수) - (4) (0) | 2025.03.05 |