python - 如何使用 Python 3 将 JSON 文件转换为字典

标签 python json list

第一篇文章在这里。 Python 和一般编程方面的完全新手。

基本上我正在关注这个人的 tutorial (不过,不查询相同的 API)关于从 Python 中的 JSON 响应中提取数据

这是我的(非常简单)代码:

#!/usr/bin/env python
import json
import requests

url = 'http://calendar.voyages-sncf.com/cdp/api/proposals/v3/outward/FRPAR/FRGNL/2017-11-01/12-HAPPY_CARD/2/fr/fr?fareCodes=HC16&onlyDirectTrains=true'

json_data = requests.get(url).json()
json_segments = json_data['segments'] 

print (json_segments)

现在,不再提取 JSON 文件中标有“Segments”的数据。我收到此错误:

json_segments = json_data['status']
TypeError: list indices must be integers or slices, not str

所以,我尝试过 int(),使其成为整数,但不起作用。

如果您能提供帮助,非常感谢。

最佳答案

requests.get().json()返回的数据是一个数据列表。您可以使用 for data in json_data: 循环来迭代列表。然后您可以直接访问字典的“segments”键。

#!/usr/bin/env python
import requests

url = 'http://calendar.voyages-sncf.com/cdp/api/proposals/v3/outward/FRPAR/FRGNL/2017-11-01/12-HAPPY_CARD/2/fr/fr?fareCodes=HC16&onlyDirectTrains=true'

json_data = requests.get(url).json()

for data in json_data:
    print(data['segments'])

关于您有关教程代码的问题:

import urllib.parse

import requests

address = 'lhr'
main_api = 'http://maps.googleapis.com/maps/api/geocode/json?'
url = main_api + urllib.parse.urlencode({'address': address})
json_data = requests.get(url).json()
json_status = json_data['status']
print(json_status)

google geocoding api here 的文档(他在视频中使用的 api)指定您将获得具有特定架构的字典。但是,当您从 http://calendar.voyages-sncf.com/cdp/api 获取数据时,它们不会返回相同的数据结构。在他们的例子中,它是一个字典列表。

因此,每次从不同的 api(或同一 api 中的不同端点)获取新数据时,您都会获取不同结构的数据。因此,您需要更改代码以处理每条数据。

JSON 只是一种标准方法,用于在通过网络发送后将字典、列表或其他 native (Python、Java 或您当时使用的任何语言的 native )与字符串进行更改。这可能会导致问题。特别是在 python 中,set() 不能直接更改为 JSON。它需要更改为列表,然后更改为 JSON,然后返回到列表,然后返回到另一侧的集合。

以下示例是从 Google 文档 here 复制的经过一些小的修改,使其更小、更易读。

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
         ],
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4224764,
               "lng" : -122.0842499
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4238253802915,
                  "lng" : -122.0829009197085
               },
               "southwest" : {
                  "lat" : 37.4211274197085,
                  "lng" : -122.0855988802915
               }
            }
         },
         "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

关于python - 如何使用 Python 3 将 JSON 文件转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46895204/

相关文章:

python - SQLite3executemany()在多个表上插入的生成器的高效设计

python - 通过cython从c调用python代码

python - 如果列表中的9个字符串全部被替换: do something

python - 如何使用变量将数据帧传递给函数?

php - 使用 Laravel 4 生成 RESTful 响应

r - 将列表中的所有矩阵转换为 R 中的 data.frames

Python组合目录中的所有csv文件并按日期时间排序

python - 我可以在 VBA 中使用我的 python 自定义对象吗?

javascript - 如何使用 Yesod 构建 AngularJS 应用程序

json - Amazon API Gateway : response body is not transformed when the API is called via Postman?