将json格式输出到console.log

时间:2017-06-29 12:13:14

标签: javascript jquery json

我有一个让我回到json的ajax,

我想要的是输出所有内容'路线'到console.log但我不知道该怎么做。

这是json输出:

    {
  "geocoded_waypoints": [
    {
      "geocoder_status": "OK",
      "place_id": "ChIJuVnJ34G3e0gRW_oSYLOUxEc",
      "types": [
        "premise"
      ]
    },
    {
      "geocoder_status": "OK",
      "place_id": "ChIJ0afvWH-3e0gRehrvBJAsflw",
      "types": [
        "premise"
      ]
    }
  ],
  "routes": [
    {
      "bounds": {
        "northeast": {
          "lat": 53.541228,
          "lng": -2.1114936
        },
        "southwest": {
          "lat": 53.5406464,
          "lng": -2.1120657
        }
      },
      "copyrights": "Dane do Mapy ©2017 Google",
      "legs": [
        {
          "distance": {
            "text": "0,1 km",
            "value": 112
          },
          "duration": {
            "text": "1 min",
            "value": 27
          },
          "end_address": "Broseley House, 81 Union St, Oldham OL1 1PF, Wielka Brytania",
          "end_location": {
            "lat": 53.5406464,
            "lng": -2.1120657
          },
          "start_address": "Ashton Arms, Oldham, Wielka Brytania",
          "start_location": {
            "lat": 53.5411486,
            "lng": -2.1114936
          },
          "steps": [
            {
              "distance": {
                "text": "39 m",
                "value": 39
              },
              "duration": {
                "text": "1 min",
                "value": 7
              },
              "end_location": {
                "lat": 53.54116,
                "lng": -2.1119794
              },
              "html_instructions": "Kieruj się <b>Clegg St</b> na <b>północny zachód</b> w stronę <b>Ascroft St</b>",
              "polyline": {
                "points": "egxeIxk{KEBEDADAF?H@JJr@"
              },
              "start_location": {
                "lat": 53.5411486,
                "lng": -2.1114936
              },
              "travel_mode": "DRIVING"
            },
            {
              "distance": {
                "text": "52 m",
                "value": 52
              },
              "duration": {
                "text": "1 min",
                "value": 11
              },
              "end_location": {
                "lat": 53.5407078,
                "lng": -2.1117626
              },
              "html_instructions": "Skręć <b>w lewo</b> w <b>Harrison St</b>",
              "maneuver": "turn-left",
              "polyline": {
                "points": "ggxeIzn{KxAk@"
              },
              "start_location": {
                "lat": 53.54116,
                "lng": -2.1119794
              },
              "travel_mode": "DRIVING"
            },
            {
              "distance": {
                "text": "21 m",
                "value": 21
              },
              "duration": {
                "text": "1 min",
                "value": 9
              },
              "end_location": {
                "lat": 53.5406464,
                "lng": -2.1120657
              },
              "html_instructions": "Skręć <b>w prawo</b> w <b>Printer St</b>",
              "maneuver": "turn-right",
              "polyline": {
                "points": "mdxeInm{KJ|@"
              },
              "start_location": {
                "lat": 53.5407078,
                "lng": -2.1117626
              },
              "travel_mode": "DRIVING"
            }
          ],
          "traffic_speed_entry": [],
          "via_waypoint": []
        }
      ],
      "overview_polyline": {
        "points": "egxeIxk{KKHCL@TJr@xAk@J|@"
      },
      "summary": "Ascroft St i Harrison St",
      "warnings": [],
      "waypoint_order": []
    }
  ],
  "status": "OK"
}

如何对这个json进行排序,以便只输出路径中的所有内容?

的Ajax:

  function getDirections(lat, lng, destinationLat, destinationLng) {
  $.ajax({
      url: '/google',
      type: 'post',
      data: { lat: lat, lng: lng, destinationLat: destinationLat, destinationLng: destinationLng },
      dataType: 'json',
      success: function(data) { 
        console.log(data.routes);
      },
      error: function() { alert('boo!'); },
      headers: {
          'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      }  
    });
  }

控制器:

function getGoogle() {
    $lat = Input::get('lat');
    $lng = Input::get('lng');
    $destinationLat = Input::get('destinationLat');
    $destinationLng = Input::get('destinationLng');
    $google = file_get_contents('https://maps.googleapis.com/maps/api/directions/json?origin='.$lat.','.$lng.'&destination='.$destinationLat.','.$destinationLng.'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50');
    return response()->json(['data' => $google]);
}

//修改

的console.log(数据);

Object {data: "{↵   "geocoded_waypoints" : [↵      {↵         "ge…t_order" : []↵      }↵   ],↵   "status" : "OK"↵}↵"}data: "{↵   "geocoded_waypoints" : [↵      {↵         "geocoder_status" : "OK",↵         "place_id" : "ChIJuVnJ34G3e0gRW_oSYLOUxEc",↵         "types" : [ "premise" ]↵      },↵      {↵         "geocoder_status" : "OK",↵         "place_id" : "ChIJ0afvWH-3e0gRehrvBJAsflw",↵         "types" : [ "premise" ]↵      }↵   ],↵   "routes" : [↵      {↵         "bounds" : {↵            "northeast" : {↵               "lat" : 53.541228,↵               "lng" : -2.1114828↵            },↵            "southwest" : {↵               "lat" : 53.5406464,↵               "lng" : -2.1120657↵            }↵         },↵         "copyrights" : "Map data ©2017 Google",↵         "legs" : [↵            {↵               "distance" : {↵                  "text" : "0.1 km",↵                  "value" : 114↵               },↵               "duration" : {↵                  "text" : "1 min",↵                  "value" : 27↵               },↵               "end_address" : "Broseley House, 81 Union St, Oldham OL1 1PF, UK",↵               "end_location" : {↵                  "lat" : 53.5406464,↵                  "lng" : -2.1120657↵               },↵               "start_address" : "Ashton Arms, Oldham, UK",↵               "start_location" : {↵                  "lat" : 53.5411291,↵                  "lng" : -2.1114828↵               },↵               "steps" : [↵                  {↵                     "distance" : {↵                        "text" : "41 m",↵                        "value" : 41↵                     },↵                     "duration" : {↵                        "text" : "1 min",↵                        "value" : 7↵                     },↵                     "end_location" : {↵                        "lat" : 53.54116,↵                        "lng" : -2.1119794↵                     },↵                     "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eClegg St\u003c/b\u003e toward \u003cb\u003eAscroft St\u003c/b\u003e",↵                     "polyline" : {↵                        "points" : "agxeIvk{KIDEDADAF?H@JJr@"↵                     },↵                     "start_location" : {↵                        "lat" : 53.5411291,↵                        "lng" : -2.1114828↵                     },↵                     "travel_mode" : "DRIVING"↵                  },↵                  {↵                     "distance" : {↵                        "text" : "52 m",↵                        "value" : 52↵                     },↵                     "duration" : {↵                        "text" : "1 min",↵                        "value" : 11↵                     },↵                     "end_location" : {↵                        "lat" : 53.5407078,↵                        "lng" : -2.1117626↵                     },↵                     "html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eHarrison St\u003c/b\u003e",↵                     "maneuver" : "turn-left",↵                     "polyline" : {↵                        "points" : "ggxeIzn{KxAk@"↵                     },↵                     "start_location" : {↵                        "lat" : 53.54116,↵                        "lng" : -2.1119794↵                     },↵                     "travel_mode" : "DRIVING"↵                  },↵                  {↵                     "distance" : {↵                        "text" : "21 m",↵                        "value" : 21↵                     },↵                     "duration" : {↵                        "text" : "1 min",↵                        "value" : 9↵                     },↵                     "end_location" : {↵                        "lat" : 53.5406464,↵                        "lng" : -2.1120657↵                     },↵                     "html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003ePrinter St\u003c/b\u003e",↵                     "maneuver" : "turn-right",↵                     "polyline" : {↵                        "points" : "mdxeInm{KJ|@"↵                     },↵                     "start_location" : {↵                        "lat" : 53.5407078,↵                        "lng" : -2.1117626↵                     },↵                     "travel_mode" : "DRIVING"↵                  }↵               ],↵               "traffic_speed_entry" : [],↵               "via_waypoint" : []↵            }↵         ],↵         "overview_polyline" : {↵            "points" : "agxeIvk{KOJCL@TJr@xAk@J|@"↵         },↵         "summary" : "Ascroft St and Harrison St",↵         "warnings" : [],↵         "waypoint_order" : []↵      }↵   ],↵   "status" : "OK"↵}↵"__proto__: Objectconstructor: function Object()hasOwnProperty: function hasOwnProperty()isPrototypeOf: function isPrototypeOf()propertyIsEnumerable: function propertyIsEnumerable()toLocaleString: function toLocaleString()toString: function toString()valueOf: function valueOf()__defineGetter__: function __defineGetter__()__defineSetter__: function __defineSetter__()__lookupGetter__: function __lookupGetter__()__lookupSetter__: function __lookupSetter__()get __proto__: function __proto__()set __proto__: function __proto__()

5 个答案:

答案 0 :(得分:2)

请检查以下可能对您有帮助的事情。在JSON响应中,您通过响应传递data密钥,因此在ajax部分您必须使用data.data.routes来获得正确的输出。

function getGoogle() {
    $lat = Input::get('lat');
    $lng = Input::get('lng');
    $destinationLat = Input::get('destinationLat');
    $destinationLng = Input::get('destinationLng');
    $google = file_get_contents('https://maps.googleapis.com/maps/api/directions/json?origin=' . $lat . ',' . $lng . '&destination=' . $destinationLat . ',' . $destinationLng . '&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50');
    return response()->json(['data' => json_decode($google)]);
 // Google's response by default is in JSON, so I've converted to array `json_decode($google)`.
}

//Here is the json response you get from ajax success.
var json = {
  "geocoded_waypoints": [
    {
      "geocoder_status": "OK",
      "place_id": "ChIJuVnJ34G3e0gRW_oSYLOUxEc",
      "types": [
        "premise"
      ]
    },
    {
      "geocoder_status": "OK",
      "place_id": "ChIJ0afvWH-3e0gRehrvBJAsflw",
      "types": [
        "premise"
      ]
    }
  ],
  "routes": [
    {
      "bounds": {
        "northeast": {
          "lat": 53.541228,
          "lng": -2.1114936
        },
        "southwest": {
          "lat": 53.5406464,
          "lng": -2.1120657
        }
      },
      "copyrights": "Dane do Mapy ©2017 Google",
      "legs": [
        {
          "distance": {
            "text": "0,1 km",
            "value": 112
          },
          "duration": {
            "text": "1 min",
            "value": 27
          },
          "end_address": "Broseley House, 81 Union St, Oldham OL1 1PF, Wielka Brytania",
          "end_location": {
            "lat": 53.5406464,
            "lng": -2.1120657
          },
          "start_address": "Ashton Arms, Oldham, Wielka Brytania",
          "start_location": {
            "lat": 53.5411486,
            "lng": -2.1114936
          },
          "steps": [
            {
              "distance": {
                "text": "39 m",
                "value": 39
              },
              "duration": {
                "text": "1 min",
                "value": 7
              },
              "end_location": {
                "lat": 53.54116,
                "lng": -2.1119794
              },
              "html_instructions": "Kieruj się <b>Clegg St</b> na <b>północny zachód</b> w stronę <b>Ascroft St</b>",
              "polyline": {
                "points": "egxeIxk{KEBEDADAF?H@JJr@"
              },
              "start_location": {
                "lat": 53.5411486,
                "lng": -2.1114936
              },
              "travel_mode": "DRIVING"
            },
            {
              "distance": {
                "text": "52 m",
                "value": 52
              },
              "duration": {
                "text": "1 min",
                "value": 11
              },
              "end_location": {
                "lat": 53.5407078,
                "lng": -2.1117626
              },
              "html_instructions": "Skręć <b>w lewo</b> w <b>Harrison St</b>",
              "maneuver": "turn-left",
              "polyline": {
                "points": "ggxeIzn{KxAk@"
              },
              "start_location": {
                "lat": 53.54116,
                "lng": -2.1119794
              },
              "travel_mode": "DRIVING"
            },
            {
              "distance": {
                "text": "21 m",
                "value": 21
              },
              "duration": {
                "text": "1 min",
                "value": 9
              },
              "end_location": {
                "lat": 53.5406464,
                "lng": -2.1120657
              },
              "html_instructions": "Skręć <b>w prawo</b> w <b>Printer St</b>",
              "maneuver": "turn-right",
              "polyline": {
                "points": "mdxeInm{KJ|@"
              },
              "start_location": {
                "lat": 53.5407078,
                "lng": -2.1117626
              },
              "travel_mode": "DRIVING"
            }
          ],
          "traffic_speed_entry": [],
          "via_waypoint": []
        }
      ],
      "overview_polyline": {
        "points": "egxeIxk{KKHCL@TJr@xAk@J|@"
      },
      "summary": "Ascroft St i Harrison St",
      "warnings": [],
      "waypoint_order": []
    }
  ],
  "status": "OK"
};
for(var jsonvalue in json.routes){
var legs = json.routes[jsonvalue].legs;
    if(legs.length){
        for(var legvalue in legs){
        $("ul").append("<li>Distance : " + legs[legvalue].distance.text + " -- Duration : " +legs[legvalue].duration.text + " </li>")
        }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
</ul>

答案 1 :(得分:0)

假设您有一个Object {}(而不仅仅是一串文本),您应该能够做到

console.log(Object.routes) 

答案 2 :(得分:0)

我认为成功承诺你没有获得正确的数据格式,你期望在console.log中成功承诺调试点,并检查对象的结构并选择路由。

`success: function(data) { 
        console.log(data.routes);
 }`

答案 3 :(得分:0)

您可以使用以下命令获取格式化的精简输出

var formatted = JSON.stringify(data, 
    function(key, value) {
        // remove geocoded_waypoints
        if (key == "geocoded_waypoints") return;
        // remove other branches...
    return value;},
    2);

...或者只返回你需要的几把钥匙。

来源:W3C

答案 4 :(得分:-2)

只是解析你的回复:

var res=JSON.parse(response);