import json
1.우선 json 파일 read
fs = open('L3-12.json') data = fs.read()
2.read한 str을 json.loads() 수행
json.loads(data)
file pointer를 이용한 직접 전달은
json.load(fs)
또는
[json.loads(line) for line in open('L3-12.json')]
그런데 encoding 문제로 utf-8-sig로 변경
fs = open('L3-12.json', encoding='utf-8-sig')
하지만 이역시도 간혹 json 문법에 맞지 않으면 error발생됨
ex)
{ "test" : 1, }
마지막 element인데도 불구하고 , 가 있기에 error발생
- json file로 write하기
– mode=’x’ : create file의 file handle전달
– indent=2 : indent된 json output출력
– sort_keys=True : key 값으로 sort 후 출력
json.dump(j, open('result.json', mode='x'), indent=2, sort_keys=True)