Python - json 파일 읽기
# json 파일 읽기
# csv : , 기준으로 데이터 분리 저장
# excel: 이진 파일, 메모장에서 볼 수 없음. 유틸리티 필요함
# => 컬럼 기준으로 데이터의 의미부여
# 단어 자체에 의미 부여 : 홍길동, 80, A, 170
# xml 문서로 저장
# <이름>홍길동</이름><몸무게>80</몸무게><학점>A</학점><키>170</키>
# json 문서로 저장 #텍스트 문서임
'''
{
"이름":'홍길동',
"몸무게":80,
"학점":"A",
"키":170
}
'''
### json 형태의 파일 읽기
df3 = pd.read_json("read_json_sample.json")
df3
### json 데이터 연습
import json
price = {
"date" : "2021-02-17",
"price" :{
"Apple":800,
"Orange":1000,
"Banana":500
}
}
print(price)
# price 객체를 이용하여 result 데이터 프레임 생성하기
import pandas as pd
result = pd.DataFrame(price)
print(result)
# 날짜 조회하기print("날짜 :",price["date"])
# 사과 가격 조회하기
print("사과 가격 :", price["price"]["Apple"])
# 과일 이름 => 과일 가격 형식으로 모두 조회하기
# Apple => 800
# Orange => 1000
# Banana => 500 결과 출력하기
print("Apple =>",price["price"]["Apple"])
print("Orange =>",price["price"]["Orange"])
print("Banana =>",price["price"]["Banana"])
#1
for f in price["price"]:
print("%s=>%s" % (f,price["price"][f]))
#2
for f in price["price"].keys():
print("%s=>%s" % (f,price["price"][f]))
#3
for k,p in price["price"].items():
print("%s=>%s" % (k,p))
# price 딕셔너리 객체를 파일로 저장하기
json.dump(price, open("price.json","w"))
# price.json 파일을 읽어서 df2 데이터프레임 객체 생성하기
df2 = pd.read_json("price.json")
df2
# json 형태의 문자열 데이터를 json 객체로 변경하기
str1 = """{
"data" : "2021-06-22",
"price" : {
"Apple":800,
"Orange":1000,
"Banana":500
}
}
"""
# str1을 딕셔너리형인 price2로 변경하기
price2 = json.loads(str1)
print(type(price2))
print(price2)
# price2 데이터를 json 형태의 price2.json 파일로 생성하기
json.dump(price2,open("price2.json","w"))