当我用邮递员调用 Google的 Distance Matrix
API时,我得到了正确的JSON响应。
API端点
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=[API KEY]
响应
{
"destination_addresses": [
"New York, NY, USA"
],
"origin_addresses": [
"Washington, DC, USA"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "228 mi",
"value": 367435
},
"duration": {
"text": "3 hours 43 mins",
"value": 13385
},
"status": "OK"
}
]
}
],
但是当我使用 APIView 类在DRF中执行相同操作时,我得到了一些奇怪的\n
作为响应。
APIView
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
class TestView(APIView):
def get(self, request, format=None):
data={}
data['destinations'] =[
'Nashik+Maharashtra',
'Mumbai+Maharashtra',
'Nagpur+Maharashtra',
'Malegaon+Maharashtra'
]
data['origins'] = "Pune+Maharashtra"
params ={
"units":"metrix",
"origins":data['origins'],
"destinations":data['destinations'],
"key":"AIzaSyDqf9R6mFSDrwqjM7iXv289o9KEdvEEmM8"
}
response = requests.get("https://maps.googleapis.com/maps/api/distancematrix/json?", params)
return Response(response.text)
响应
"{\n \"destination_addresses\" : [ \"Nashik, Maharashtra, India\" ],\n \"origin_addresses\" : [ \"Pune, Maharashtra, India\" ],\n \"rows\" : [\n {\n \"elements\" : [\n {\n \"distance\" : {\n \"text\" : \"212 km\",\n \"value\" : 212479\n },\n \"duration\" : {\n \"text\" : \"4 hours 19 mins\",\n \"value\" : 15531\n },\n \"status\" : \"OK\"\n }\n ]\n }\n ],\n \"status\" : \"OK\"\n}\n"
如何获取适当的JSON响应。
答案 0 :(得分:0)
使用response.json()
代替response.text
答案 1 :(得分:-2)
“怪异\n
”是换行符的转义序列。由于响应是字符串,因此它使用\n
表示换行符。要理解我的意思,请尝试打印响应,然后以与您的第一个响应相同的格式向您显示。