我正在构建我的第一个网络刮刀,并让以下内容返回我需要的信息 -
import requests
r = requests.get('https://greatbritishpublictoiletmap.rca.ac.uk/loos/54c234f02ec4abe957b84f37?format=json')
r.json()["properties"]
输出看起来像这样 -
{'orig': {'amenity': 'toilets', 'source': 'survey', 'id': 'node/975749026', 'location': 'Victoria Street', 'postcode': 'DE1 1EQ', 'open': '07.00 - 19.00', 'closed': '19.00 - 07.00', 'male': '1', 'female': '1', 'unisex': '0', 'disabled': '1', 'radar': 'Yes', 'baby change': '0', 'cost': '�0.20', 'date': '15/04/2014', 'data collected from': 'FOI', 'geocoded': True, 'geocoding_method': 'postcode'}, 'geocoding_method': 'postcode', 'geocoded': True, 'fee': '�0.20', 'babyChange': 'false', 'radar': 'true', 'type': 'female and male', 'opening': '07:00-19:00', 'postcode': 'DE1 1EQ', 'name': 'Victoria Street', 'streetAddress': 'Victoria Street', 'accessibleType': '', 'notes': '', 'area': [{'type': 'Unitary Authority', 'name': 'Derby City Council', '_id': '57f268ed87986b0010177619'}], 'access': 'public', 'active': True}
我只是想将这些信息转储到CSV中,但我很难调整我的代码。我该怎么做?
答案 0 :(得分:0)
您确实需要决定所需的数据,以及在JSON嵌套时如何格式化。例如,以下方法只是简单地写入字符串或布尔值的所有条目:
import requests
import csv
r = requests.get('https://greatbritishpublictoiletmap.rca.ac.uk/loos/54c234f02ec4abe957b84f37?format=json')
properties = r.json()["properties"]
with open('output.csv', 'w', newline='', encoding='utf-8') as f_output:
csv_output = csv.writer(f_output)
header = []
for k, v in properties.items():
if isinstance(v, str) or isinstance(v, bool):
header.append(k)
csv_output.writerow(header)
csv_output.writerow([properties[k] for k in header])
这将为您提供如下CSV:
opening,name,radar,active,accessibleType,type,postcode,geocoding_method,babyChange,notes,fee,geocoded,access,streetAddress
07:00-19:00,Victoria Street,true,True,,female and male,DE1 1EQ,postcode,false,,�0.20,True,public,Victoria Street
使用Python 3.5.2进行测试