python json模組簡單運用

來源:互聯網
上載者:User

從本地中讀入json格式檔案,然後轉換成python的格式,對其進行刪除,修改之後,再次以json的格式編碼,並寫入檔案

PS:JSON 是用來進行資料轉換的,第一次遇見 思路: 從json檔案中讀取 將json轉換成python的資料結構,對其內容進行修改,然後再編碼成json 將json寫入檔案

原檔案內容:

{“weather”:{“city”:”泰興”,”溫度”:”-1~-5攝氏度”,”風力”:”3-4級”}}

修改之後,在寫入:

{“weather”:{“city”:”泰興”,”溫度”:”-1~-5攝氏度”,”風力”:”3-4級”}}
{“溫度”: “-1~-5攝氏度”, “city”: “南京”, “風力”: “3-4級”} 代碼:

import jsondef fetch_data():    f = open('/home/dream/案頭/weather.json')    data = f.read()    print('以字串形式讀出.json成功')    return datadef select_data(data_json):    temp = json.loads(data_json)    data_python = temp['weather']    data_python['city'] = '南京'    json_data = json.dumps(data_python,ensure_ascii=False)    print('提取天氣資料,並修改城市成功')    return json_datadef write_data(data_changed):    f = open('/home/dream/案頭/weather.json','a+')    f.write(data_changed)    f.close()    print('寫入成功')data = fetch_data()result= select_data(data)write_data(result)
總結:

簡單的操作並不難,關鍵是要弄清楚幾個小點 loads()用來返回python的格式,解碼。 dumps()是編碼,將python格式轉換成json格式的 字串,這一點挺重要的。 ensure_ascii=Flase.預設是用ASCII來編碼的,因為有中文所以False。關掉。

作為剛開始編程的我,不得不承認還差很多,不過慢慢來總會改善的。在取函數名字的時候,我就發現真的難啊,也是一門學問呢~加油~共勉~還有直接對檔案的操作,差不多,就不再舉例了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.