Python json 메모

jody·2023년 5월 9일

코딩메모

목록 보기
1/7

쓸 때 마다 헷갈려서 적어둔다...

json 파일

json은 딕셔너리 값 하나를 가지거나 여러가지 값을 가진 리스트를 가질 수 있다.
그래서 처음 파일을 만들 때 내용이 비었어도 리스트나 딕셔너리 표시를 해줘야 한다

{}

위 json 파일에 값 넣기

import json

dog_dict = {}
dog_dict["name"]= "happy"
dog_dict["year"]=2

#json 파일 가져오기
with open("Test.json") as f: 
    json_object = json.load(f)

#값 넣기
json_object["what"] = 1
json_object["dog"] = dog_dict

#json 파일 저장
with open("Test.json",'w') as f:
    json.dump(json_object, f, indent=2)

결과:

{
  "what": 1,
  "dog": {
    "name": "happy",
    "year": 2
  }
}

딕셔너리 안에 여러가지 값을 넣을 수 있다. 딕셔너리 형식이기 때문에 안에 들어가는 값은 뭐가 됐든 이름을 정해줘야 한다.

또는 배열을 사용할 수 있다. 리스트 내의 값은 이름을 갖지 않는다.

[
  {},
  []
]

위 json 파일에 값 넣기

import json

dog_dict = {}
dog_dict["name"]= "happy"
dog_dict["year"]=2

some_list = ["a","b","c"]

#json 파일 가져오기
with open("Test.json") as f:
    json_object = json.load(f)
    
#값 넣기
json_object.append(dog_dict)
json_object.append(some_list)
json_object.append(1)

#json 파일 저장
with open("Test.json",'w') as f:
    json.dump(json_object, f, indent=2)

결과:

[
  {},
  [],
  {
    "name": "happy",
    "year": 2
  },
  [
    "a",
    "b",
    "c"
  ],
  1
]

저장시 한글 인코딩 에러 및 공백 설정

인코딩 에러 ensure_ascii=False
공백 설정 indent=4

with open("test.json",'w') as f:
	json.dump(json_object, f, ensure_ascii=False,indent=4)

json 파일 로드 시 'cp949' codec can't decode byte 0xed in position 19: illegal multibyte sequence 에러

열 때 encoding='UTF8' 추가

with open('data.json',encoding='UTF8') as f:

0개의 댓글