쿼리 된 오픈 소스 데이터 (here, for reference)를 csv로 변환하려고합니다. 나는 다음과 같이 requests
패키지를 사용하여 데이터를 액세스하고 조회 할 수있어 : 데이터의Python에서 JSON을 CSV로 변환하여 내 보낸 필드 내 사전 처리
import requests
import gzip
import csv
url = "https://data.cityofchicago.org/resource/6zsd-86xi.json"
response = requests.get(url)
print response.status_code
if response.status_code == 200:
print "Connection successful. Decoding JSON"
data = response.json()
각 행은 존재할 수도 있고 존재하지 않을 수도있다 (22) 열까지있다. 열에 대한 데이터가 없으면 JSON 쌍이 존재하지 않아 KeyErrors가 발생합니다. , 나는 field_names
와 restval=None
매개 변수를 사용하여 csv.DictWriter
클래스 사용하고 시도하고이 문제를 해결하려면, '위치'그러나 마지막 열이 데이터를 기록
field_names = ['id',
'case_number',
'date',
'block',
'iucr',
'primary_type',
'description',
'location_description',
'arrest',
'domestic',
'beat',
'district',
'ward',
'community_area',
'fbi_code',
'x_coordinate',
'y_coordinate',
'year',
'updated_on',
'latitude',
'longitude',
'location'
]
file_name = 'open_data_test.csv.gz'
local_file = gzip.open('/tmp/' + file_name, "wb")
output = csv.DictWriter(local_file,
fieldnames=field_names,
restval=None,
extrasaction='ignore',
delimiter='|',
quoting=csv.QUOTE_ALL,
quotechar='"',
doublequote=True,
lineterminator='\n')
for row in data:
output.writerow(row)
그 자체는 "유형"과 "좌표를 포함하는 사전입니다 "(예 : "{u'type': u'Point', u'coordinates': [-87.711766, 41.880909]}"
). 존재하는 경우에만 '좌표'데이터 만 원합니다.
데이터가있는 경우 어떻게하면이 열의 '좌표'섹션 만 출력 파일에 쓸 수 있습니까? field_names
을 편집하여 'location'[1]
또는 'location'['coordinates']
을 포함시키지 않는 것 같습니다.
) (당신의'dict.keys 통해 반복에 대해 '면,'키 =='coordinates''는'쓰기 만하는 방법 dict [ 'coordinates']'? –
'행의 '위치'인 경우 : row [ 'location'] = 행 [ 'location'] [ 'coordinates']' –