파이썬 json 특정값 추출
조회수 10675회
{
"test": [
{
"customer": "test1",
"type": [
"windows"
],
"contact": [{
"name": "a",
"email": "@gmail.com",
"phone": null ,
"remarks": null
}]
},
{
"customer": "test2",
"type": [
"android"
],
"contact": [{
"name": "b",
"email": "@gmail.com",
"phone": "010-0000-0000",
"remarks": null
}]
},
{
"customer": "test3",
"type": [
"android"
],
"contact": [{
"name": "a",
"email": "@naver.com",
"phone": null,
"remarks": null
}]
}
]
}
import json
with open('test.json', 'rt', encoding='UTF8') as f:
content = json.load(f)
email_list = [ x for x in content['omnidoc']['contact']['email'].keys()]
파이썬에서 json파일의 email데이터만 리스트로 가져오고 싶은데 어떻게 해야할까요? 그리고 중복제거까지 하고싶어요.
여기서는 이런 오류가 나오네요.
TypeError: list indices must be integers or slices, not str
1 답변
-
참고하세요.
import json from pprint import pprint s = '''{ "test": [ { "customer": "test1", "type": [ "windows" ], "contact": [{ "name": "a", "email": "@gmail.com", "phone": null , "remarks": null }] }, { "customer": "test2", "type": [ "android" ], "contact": [{ "name": "b", "email": "@gmail.com", "phone": "010-0000-0000", "remarks": null }] }, { "customer": "test3", "type": [ "android" ], "contact": [{ "name": "a", "email": "@naver.com", "phone": null, "remarks": null }] } ] }''' d = json.loads(s) print('------') pprint(d) print('------') for e in d['test']: pprint(e['contact']) print('------') for i, e in enumerate(d['test']): print(i, e['contact'][0]['email']) print('------') emails = { e['contact'][0]['email'] for e in d['test']} print(emails) print('------')
결과.
------ {'test': [{'contact': [{'email': '@gmail.com', 'name': 'a', 'phone': None, 'remarks': None}], 'customer': 'test1', 'type': ['windows']}, {'contact': [{'email': '@gmail.com', 'name': 'b', 'phone': '010-0000-0000', 'remarks': None}], 'customer': 'test2', 'type': ['android']}, {'contact': [{'email': '@naver.com', 'name': 'a', 'phone': None, 'remarks': None}], 'customer': 'test3', 'type': ['android']}]} ------ [{'email': '@gmail.com', 'name': 'a', 'phone': None, 'remarks': None}] [{'email': '@gmail.com', 'name': 'b', 'phone': '010-0000-0000', 'remarks': None}] [{'email': '@naver.com', 'name': 'a', 'phone': None, 'remarks': None}] ------ 0 @gmail.com 1 @gmail.com 2 @naver.com ------ {'@gmail.com', '@naver.com'} ------
댓글 입력