json对使用过的词典的回应

时间:2017-09-08 13:41:13

标签: python json dictionary

所以我试图解析以下响应(JSON响应),这是一个示例:

{
  "kind": "youtube#searchListResponse",
  "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/fywkWrox-IkW0v2IWY27RMiWvvA\"",
  "nextPageToken": "CBQQAA",
  "regionCode": "IQ",
  "pageInfo": {
    "totalResults": 1000000,
    "resultsPerPage": 20
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/j0uEstXCXOhrDqDegEBmEeHqsBM\"",
      "id": {
        "kind": "youtube#video",
        "videoId": "YQHsXMglC9A"
      },
      "snippet": {
        "publishedAt": "2015-10-23T06:54:18.000Z",
        "channelId": "UComP_epzeKzvBX156r6pm1Q",
        "title": "Adele - Hello",
        "description": "'Hello' is taken from the new album, 25, out November 20. http://adele.com Available now from iTunes http://smarturl.it/itunes25 Available now from Amazon ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/YQHsXMglC9A/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/YQHsXMglC9A/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/YQHsXMglC9A/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "AdeleVEVO",
        "liveBroadcastContent": "none"
      }
    } 

这是我的解析功能:

  def parse(self):
        items = self['items']
        i = 0
        for item in items:
            Data = {str(i): {
                "id": item['id']['videoId'],
                "title": item['snippet']['title'],
                "description": item['snippet']['description'],
                "thumbnail": item['snippet']['thumbnails']['medium']['url'],
                "publishedAt": item['snippet']['publishedAt'],
                "FullURL": "https://www.youtube.com/watch?v=" + item['id']['videoId']
            }}
            i = i +1
        return Data

主要问题是字典只插入响应的最后一位,例如,我提取10个结果,并且它只返回最后一个响应。问题是什么?

1 个答案:

答案 0 :(得分:0)

Data循环中取出for的定义,将其初始化为空字典,然后在每次迭代时为其添加键/值对。目前,您继续在每个循环上重新定义整个字典,包含单个条目。然后,您最终return最终版本。

def parse(self):
        items = self['items']
        Data = {} # Initialise it here
        for i, item in enumerate(items): # Now you don't need to increment i
            # Insert your key/value pair
            Data[str(i)] = {
                "id": item['id']['videoId'],
                "title": item['snippet']['title'],
                "description": item['snippet']['description'],
                "thumbnail": item['snippet']['thumbnails']['medium']['url'],
                "publishedAt": item['snippet']['publishedAt'],
                "FullURL": "https://www.youtube.com/watch?v=" + item['id']['videoId']
            }

        return Data