개발자 미니민의 개발스터디

[파이썬] JSON

by mini_min
[파이썬] JSON 

🖋️ JSON 변환

: 파이썬 dict 객체를 JSON 형식의 문자열로 반환

JSON 모듈의 dumps 함수를 이용한다. dict 파이썬 객체를 json 형식의 문자열로 반환한다. 

한글로 출력하려면 ensure_ascii 를 사용한다.

import json

#파이썬 객체를 JSON으로 변환 : 인코딩
#   json 모듈의 dumps 함수 이용 

# dict 객체
std = {
    'hak':'1001',
    'name':'이자바',
    'score':[
        {'subject':'kor', 'grade':4.0},
        {'subject':'eng', 'grade':3.5},
        {'subject':'mat', 'grade':4.5}
    ]
}

#파이썬 dict 객체를 json 형식의 문자열로 반환
json_str = json.dumps(std)
    #한글은 유니코드로 변환된다.
print(json_str)
print("----------------")

# 한글을 유니코드가 아닌 한글로 변환
json_str = json.dumps(std, ensure_ascii=False)
print(json_str)
print("----------------")

print(type(json_str)) #<class 'str'>

 

: JSON 문자열을 파이썬 객체로 변환 (디코딩) 은 JSON 모듈의 oads 함수를 이용한다.

import json
#JSON 형식의 문자열을 Python 객체로 변환 : 디코딩
#   : json 모듈의 oads함수를 이용

json_str = """
{
    "hak":"1001",
    "name":"이자바",
    "score":[
        {"subject":"kor", "grade":4.0},
        {"subject":"eng", "grade":3.5},
        {"subject":"mat", "grade":4.5}
    ]
}
"""

# json 형식의 문자열을 파이썬 객체로 변환
std_data = json.loads(json_str)
print(std_data)
print("---------")

print(type(std_data))
print(std_data['hak'])
print(std_data.get("name"))
print(std_data.get("score"))
print("-----------")

for item in std_data["score"]:
    print(item.get("subject"), item["grade"])

 

: 파이썬 객체를 JSON 형식의 문자열로 파일에 저장한다.

# Python 객체를 JSON 형식의 문자열로 파일에 저장하기

import json

json_obj = { #dict
    "id":1,
    "username":"이자바",
    "email":"test@test.com",
    "address":{
        "addr1":"서울시 마포구",
        "addr2":"몰라로 100",
        "zipcode":"12345"
    },
    "admin":False,
    "hobbies":None
    
}

pathname = "C:/source/data/output.json"
with open(pathname, "w", encoding="utf-8") as f:
    # Python 객체를 JSON 형식의 문자열로 파일에 저장하기
    json.dump(json_obj, f, ensure_ascii=False, indent=2)
    
print("파일 저장 완료@")

 

: 로드하기 . load() 사용

import json

#load() : JSON 형식의 문자열로 저장된 파일을 읽어 파이썬 객체로 불러온다.
pathname = "C:/source/data/output.json"
with open(pathname, "r", encoding="utf-8") as f:
    json_object = json.load(f)
    
print(json_object)
print(type(json_object)) #<class 'dict'>

 

: csv 파일 읽어 json 파일로 저장하기

reader 로 csv 파일을 읽고, 첫줄 컬럼이름은 list 에 저장, 두번째 줄부터 zip 을 묶어서 json으로 dumps 한다. 

# csv 파일을 json 파일로 저장하기

import csv
import json

input_file = "C:/source/data/score.csv"
output_file = "C:/source/data/score.json"

with open(input_file, "r", encoding="utf-8", newline="") as i_file, \
    open(output_file, "w", encoding="utf-8", newline="") as o_file:
    
    reader = csv.reader(i_file)
    #print(type(reader)) #<class '_csv.reader'>

    # 첫줄 컬럼이름을 읽어 list에 저장
    col_names = next(reader)
    # print(col_names)
        
    # 두번째 줄부터 zip으로 묶어서 json으로 dumps
    # 키컬럼,값 형태로 만드는걸 zip이 해준다.
    for cols in reader:
        doc = {col_names:col for col_names, col in zip(col_names, cols)}
        print(json.dumps(doc, ensure_ascii=False), file=o_file)
            
print("파일 변환 완료..")
# csv 파일을 json 파일로 저장하기

import csv
import json

input_file = "C:/source/data/score.csv"
output_file = "C:/source/data/score.json"

with open(input_file, "r", encoding="utf-8", newline="") as i_file, \
    open(output_file, "w", encoding="utf-8", newline="") as o_file:
    
    reader = csv.DictReader(i_file)
    #print(type(reader)) #<class 'csv.DictReader'>
        
    for row in reader:
        #print(type(row))
        json_str = json.dumps(row, ensure_ascii=False)
        o_file.write(json_str+"\n")
        
print("파일 변환 완료..")

 

: json 파일을 csv 파일로 저장한다.

# json 파일을 csv 파일로 저장하기

import csv
import json

input_file = "C:/source/data/score.json"
output_file = "C:/source/data/score.csv"

with open(input_file, "r", encoding="utf-8", newline="") as i_file, \
    open(output_file, "w", encoding="utf-8", newline="") as o_file:

    data = []
    for line in i_file:
        s = json.loads(line)
        data.append(s)
    
    csvwriter = csv.writer(o_file)
    csvwriter.writerow(data[0].keys())
    for line in data:
        csvwriter.writerow(line.values())
        
print("파일 변환 완료..")

 

 

 

'Python' 카테고리의 다른 글

[파이썬] 추천 기능 서비스 (영화 추천 기능)  (0) 2023.01.12
[파이썬] 판다스 pandas  (0) 2022.12.25
[파이썬] 정규식  (0) 2022.12.25
[파이썬] 파일 처리  (1) 2022.12.25
[파이썬] 예외  (0) 2022.12.25

블로그의 정보

개발자 미니민의 개발로그

mini_min

활동하기