当通过APIView类请求get方法时,如何从API响应中删除\n或以适当的JSON格式获取响应

2024-04-25 08:07:44 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在postman中调用Google的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"
            }
         ]
      }
   ],

但是当我在我的DRF中使用APIView类做同样的事情时,我得到了一些奇怪的响应

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响应


Tags: textimportapijsondatavalueresponseaddresses
2条回答

response.json()代替response.text

“怪异的\n”是换行符的转义序列。因为响应是一个字符串,所以它使用\n来表示换行符。为了更好地理解我的意思,请尝试打印响应,它将以与第一个响应相同的格式显示给您

相关问题 更多 >