簡體   English   中英

使用Python從此JSON對象中提取嵌套列表

[英]Extract a nested list from this JSON object with Python

我正在使用這個python腳本( 嘗試 )從JSON對象中提取嵌套列表。

import json
from collections import defaultdict
from pprint import pprint

with open('data-science.txt') as data_file:
    data = json.load(data_file)

locations = defaultdict(int)

for item in data['included']:
    location = item['attributes']
    print(location)

我得到以下輸出:

{'name': 'Victoria', 'coord': [51.503378, -0.139134]}
{'name': 'United Kingdom', 'coord': None}
{'name': 'data science'}
{'CEO': None, 'abbreviation': None, 'logoUrl': None, 'title': 'Make IT London'}
{'name': 'Victoria', 'coord': [51.503378, -0.139134]}
{'name': 'United Kingdom', 'coord': None}
{'name': 'data science'}
{'CEO': None, 'abbreviation': None, 'logoUrl': None, 'title': 'Make IT London'}
{'name': 'Victoria', 'coord': [51.503378, -0.139134]}
{'name': 'United Kingdom', 'coord': None}
{'name': 'data science'}
{'CEO': None, 'abbreviation': None, 'logoUrl': None, 'title': 'Make IT London'}
{'name': 'Victoria', 'coord': [51.503378, -0.139134]}
{'name': 'United Kingdom', 'coord': None}
{'name': 'data science'}
{'CEO': None, 'abbreviation': None, 'logoUrl': None, 'title': 'Make IT London'}
{'name': 'Victoria', 'coord': [51.503378, -0.139134]}
{'name': 'United Kingdom', 'coord': None}
{'name': 'data mining'}
{'name': 'data analysis'}

但我真正想要的是與"id"相關聯的'coord'列表。

單個記錄如下所示:

    {
        "id": 3,
        "type": "location",
        "attributes": {
            "name": "Victoria",
            "coord": [
                51.503378,
                -0.139134
            ]
        }
    },

我怎樣才能提取出唯一的"id": 3"coord": [ 51.503378, -0.139134 ]

這有點勉強但可能有所幫助。 基線 - 你可能想在python中使用get函數。 (見: https//docs.python.org/2/library/stdtypes.html#dict.get

我不會在下面的代碼上擴展太多 - 它相當簡單 - 但是你可以在它周圍添加一些邏輯來檢查id是否為None或者coord是None並且為了你自己的目的進行額外的處理。

for record in data['included']:
    id = record.get('id', None)
    coord = record.get('attributes', {}).get('coord', None)

您必須使用其鍵訪問子結構:

coords = {}
for item in data['included']:
    coords[item['id']] = item['attributes']['coords']
>>> data
{'id': 3, 'attributes': {'coord': [51.503378, -0.139134], 'name': 'Victoria'}, 'type': 'location'}
>>> from operator import itemgetter
>>> my_id = itemgetter('id')
>>> attributes = itemgetter('attributes')
>>> coord = itemgetter('coord')
>>> 
>>> my_id(data), coord(attributes(data))
(3, [51.503378, -0.139134])
>>> {my_id(data) : coord(attributes(data))}
{3: [51.503378, -0.139134]}
>>> d = {}
>>> d[my_id(data)] = coord(attributes(data))
>>> d
{3: [51.503378, -0.139134]}
>>> 

我假設, idtype總是通過JSON響應提供,如果typelocation那么coord也將被給出:

location_map = {}

for item in data.get('included', [])
    if item['type'] == 'location':
        location_map[item['id']] = item['attributes']['coord']

print location_map

或者以更加pythonic的方式:

location_map = {
    item['id']: item['attributes']['coord']
    for item in data.get('included', []) if item['type'] == 'location'
}
print location_map

對於樣本輸入:

[
  {
    "id": 3,
    "type": "location",
    "attributes": {
        "name": "Victoria",
        "coord": [
            51.503378,
            -0.139134
        ]
     }
  }
]

結果將是:

{3: [51.503378, -0.139134]}

供參考,請參閱Dict理解: https//www.python.org/dev/peps/pep-0274/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM