简体   繁体   English

从json输出获取特定数据

[英]Get specific data from json output

I'm using this code to get specific data. 我正在使用此代码来获取特定数据。

#!/usr/bin/env python3

import requests as req
import json


with open("query4.txt", "r") as f_input:
     # content = f_input.read()
     # a = content[:].split(',')
     for id in f_input:

     # data = {'coordinates': '38.48511505, 48.94205856' '|' '38.49207300, 48.94167600', 'profile': 'driving-car'}
          url = "https://api.openrouteservice.org/directions?api_key=5b3ce3597851110001cf62483bc257e622284e54ae3004682db1a018&coordinates={}&profile=driving-car".format(id.strip())
          resp = req.get(url, headers = {'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8'})
          print(resp.status_code, resp.reason)
          print(resp.url)
          print(resp.text)

How can I write the output which is looking like this 我怎么写这样的输出

{"routes":[{"summary":{"distance":388.6,"duration":49.3},"geometry_format":"encodedpolyline","geometry":"uqjrHegz{Dm@r@cCx@Fh@IB}A^{A`@OBuA\\MDgAZI@DeA]B","segments":[{"distance":388.6,"duration":49.3,"steps":[{"distance":107.1,"duration":19.3,"type":11,"instruction":"Head northwest","name":"","way_points":[0,2]},{"distance":15.2,"duration":3.7,"type":0,"instruction":"Turn left","name":"","way_points":[2,3]},{"distance":225.2,"duration":13.5,"type":1,"instruction":"Turn right onto Головатого вулиця","name":"Головатого вулиця","way_points":[3,11]},{"distance":25.1,"duration":9,"type":1,"instruction":"Turn right","name":"","way_points":[11,12]},{"distance":16.1,"duration":3.9,"type":0,"instruction":"Turn left","name":"","way_points":[12,13]},{"distance":0,"duration":0,"type":10,"instruction":"Arrive at your destination, on the right","name":"","way_points":[13,13]}]}],"way_points":[0,13],"bbox":[30.940011,50.358194,30.941469,50.361127]}],"bbox":[30.940011,50.358194,30.941469,50.361127],"info":{"attribution":"openrouteservice.org | OpenStreetMap contributors","engine":{"version":"5.0.1","build_date":"2019-05-29T14:22:56Z"},"service":"routing","timestamp":1568132624542,"query":{"profile":"driving-car","preference":"fastest","coordinates":[[30.941423,50.358173],[30.940412,50.361131]],"language":"en","units":"m","geometry":true,"geometry_format":"encodedpolyline","instructions_format":"text","instructions":true,"elevation":false}}}

To a file with data only from the summary: distance in text format? 对于仅包含摘要数据的文件:距离为文本格式? Thank You! 谢谢!

if the result is in a text format you need to convert it into a dict first: 如果结果为文本格式,则需要先将其转换为字典:

result = json.loads(resp.text)

And after that you get from the dict the info you need: 之后,您从字典中获取所需的信息:

with open("result.txt", "w") as f_o:
    for row in result["routes"]:
        f_o.write("distance:" + str(row["summary"]["distance"])) # depending on how do you want the result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM