2017-05-16 84 views
-3

我建立我的第一個網站刮板,並具有以下回來時,我需要的信息 -解析JSON到csv的Python

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,但我正在努力調整我的代碼。我該怎麼做呢?

+3

你測試不能調整不存在的代碼。你目前如何嘗試寫入CSV?你可以編輯你的問題,以顯示你目前使用的是什麼? – roganjosh

+1

可能重複[如何將JSON轉換爲CSV?](http://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv) –

+0

事實是,我正在學習當我去,我已經嘗試寫入CSV,但無法得到它的工作,所以沒有包括半熟的代碼,我很高興能得到這一點,因爲我第一次嘗試。只是在一個指針或2沒有什麼大不了。 – Dan

回答

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