Python 读写json文件
来源:互联网 发布:抽奖活动软件 编辑:程序博客网 时间:2024/05/23 13:15
Python 读写json文件
本文旨在记录将读入url后的json文件转为python格式从而进行分析
- 读入url,保存json文件
import urllib, jsonresponse = urllib.urlopen(url)data = json.loads(response.read())
- json切片
def dict_slice(adict, start, end): keys = adict.keys() dict_slice = {} for k in keys[start:end]: dict_slice[k] = adict[k] return dict_sliceresult = dict_slice(data, 1, 2)result = result[u'rows'][0][u'elements'][0][u'distance'][u'text']#取出json内部分内容
- json格式转为python格式
distance = json.dumps(result)#转为python格式
实例代码
该代码主要实现计算两个城市之间的距离,利用google distance matrix的api,更多应用示例见以下链接:
https://developers.google.com/maps/documentation/distance-matrix/start
该代码根据读取xls文件中的相应城市地址,从而进行计算并输出所有的距离
#!/usr/bin/env python2# -*- coding: utf-8 -*-"""Created on Sun May 21 22:49:59 2017@author: chenjingwen"""import xlrdimport numpy as npimport urllib, jsonimport csvdef dict_slice(adict, start, end): keys = adict.keys() dict_slice = {} for k in keys[start:end]: dict_slice[k] = adict[k] return dict_slicefiled = xlrd.open_workbook('Distance1.xls') # 打开xls文件table = filed.sheets()[0]nrows = table.nrowsdestination=[] originations = [] #将table中第一行的数据读取并添加到data_list中for i in range(nrows): dest = table.row_values(i)[0].encode("utf-8") origin = table.row_values(i)[1].encode("utf-8") destination.append(dest) originations.append(origin)website0 = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='#origins = 'Washington,DC'website1 = '&destinations='#destination = 'New,York,City,NY'website2 = '&key=AIzaSyD1SqEGEsCe3iaktwXALoSDx3b4JiDA0Dw'#输入apiresult = []for i in range(444,nrows): url = website0 + originations[i] + website1 + destination[i] + website2 response = urllib.urlopen(url) data = json.loads(response.read()) res = dict_slice(data, 1, 2) res = res[u'rows'][0][u'elements'][0][u'distance'][u'text'] distance = json.dumps(res) result.append([i,distance])with open('destination_result.csv','w') as f: #this will save the results of all frames,you can just uncomment it f_csv = csv.writer(f) f_csv.writerows(result)
阅读全文
0 0
- Python读写json文件
- python读写json文件
- Python读写json文件
- Python读写json文件
- Python 读写json文件
- python 读写json文件
- python读写json文件
- python dict json读写文件
- 【Python】python读写txt和json文件
- python 读写txt文件 json文件
- 用python读写yaml/json文件
- python读写word、excel、csv、json文件
- Python读写json文件的简单实现
- Python读写json格式文件
- python 读写JSON数据
- python 读写 json 解析
- Json.NET读写Json文件
- php读写json文件
- with(nolock)的用法
- android系统动态切换输入法
- bat脚本 -- iar自动查找头文件
- php文件操作
- Selected SVN connector library is not available or cannot be loaded
- Python 读写json文件
- PCA 方法及其应用
- mysql手工注入
- PyQt5初次体验
- 【数据库】深入分析事务的隔离级别
- 263. Ugly Number
- 计算样本数据的方差, 标准方差与协方差
- 【C++ STL】queue和priority_queue
- 比特币开发专题(莱特币与比特币本质上的区别)