python str 转换 json

使用Python编码和解析Json

Python内置了json包来帮助我们完成对json的操作。

针对str操作:将Python的字典结构导出到json使用json.dumps() ,将json读成Python的字典结构,使用json.loads() 。

针对对文件操作:分别使用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"}]

你可能感兴趣的:(python3.x,json)