我如何在python中使用json输出

时间:2012-06-29 07:35:45

标签: python json

我想知道如何在json中获得python输出。 这是网址:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false

其输出将是这样的

{
  "status": "OK",
  "origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
  "destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
  "rows": [ {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 340110,
        "text": "3 jours 22 heures"
      },
      "distance": {
        "value": 1734542,
        "text": "1 735 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 24487,
        "text": "6 heures 48 minutes"
      },
      "distance": {
        "value": 129324,
        "text": "129 km"
      }
    } ]
  }, {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 288834,
        "text": "3 jours 8 heures"
      },
      "distance": {
        "value": 1489604,
        "text": "1 490 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 14388,
        "text": "4 heures 0 minutes"
      },
      "distance": {
        "value": 135822,
        "text": "136 km"
      }
    } ]
  } ]
}

如何在python中打印此输出?
任何人都可以帮助我吗? 感谢

2 个答案:

答案 0 :(得分:2)

根据您的Python版本,导入JSON可能还不够。

如果您运行的是低于2.6的python版本,则需要从命令行安装simplejson。

  

pip install simplejson

之后,只需正常导入。

import simplejson as json

以下内容适用于Python 2.x. 3.x中存在一些差异,我将其留作您想象的练习。

try:
    import json
except:
    import simplejson as json
url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false"
contents = urllib2.urlopen(url).read()
json_array = json.loads(contents)
print repr(json_array)

答案 1 :(得分:0)

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')

http://docs.python.org/library/json.html

相关问题