python str 轉換 json

使用Python編碼和解析Json

Python內置了json包來幫助咱們完成對json的操做。json

針對str操做:將Python的字典結構導出到json使用json.dumps() ,將json讀成Python的字典結構,使用json.loads() 。app

針對對文件操做:分別使用json.load()函數和json.dump()函數。函數

# coding=gbk
import traceback
import json
file_name = '廣州市_農貿市場_1717.txt'
f = open(file_name, 'r')
tmp = json.load(f)
print(type(tmp))
data = []
for i in tmp:
#    print(i)
#測試作一下格式轉換
    dl = {
        "name":i["name"],
        "location_lat" : i["location"]["lat"],
        "location_lng" : i["location"]["lng"]
    }
    data.append(dl)
print(data)
with open('ceshi.txt', 'w', encoding="utf-8") as f:
    f.write(json.dumps(data, ensure_ascii=False))
    print('---wirte success---')

附上 廣州市_農貿市場_1717.txt測試

[{"name": "江南市場", "location": {"lat": 23.179127, "lng": 113.236457}, "address": "廣東省廣州市白雲區增槎路926號", "province": "廣東省", "city": "廣州市", "area": "白雲區", "street_id": "9fbfeef24609615cece4a59b", "detail": 1, "uid": "9fbfeef24609615cece4a59b"}, {"name": "廣州番禺清河市場", "location": {"lat": 22.938501, "lng": 113.401308}, "address": "廣東省廣州市番禺區亞運大道94號", "province": "廣東省", "city": "廣州市", "area": "番禺區", "street_id": "bc57b5426b43342922f01731", "telephone": "(020)84629663", "detail": 1, "uid": "bc57b5426b43342922f01731"}]
相關文章
相關標籤/搜索