Python - 将JSON元素附加到列表中

时间:2017-05-01 16:02:46

标签: python json python-2.7 list

我有一个city.json,我通过网站解析收集了它,它显示在下面

[
{"city": ["\r\nLondon\r\n"]},
{"city": ["\r\nEdinburgh\r\n"]},
{"city": ["\r\nBlackpool\r\n"]},
{"city": ["\r\nBrighton & Hove\r\n"]},
{"city": ["\r\nGlasgow\r\n"]},
{"city": ["\r\nManchester\r\n"]},
{"city": ["\r\nYork\r\n"]},
{"city": ["\r\nTorquay\r\n"]},
{"city": ["\r\nInverness\r\n"]},
{"city": ["\r\nLiverpool\r\n"]},
{"city": ["\r\nBirmingham\r\n"]},
{"city": ["\r\nBath\r\n"]},
{"city": ["\r\nScarborough\r\n"]},
{"city": ["\r\nCambridge\r\n"]},
{"city": ["\r\nNewquay\r\n"]},
{"city": ["\r\nAberdeen\r\n"]},
{"city": ["\r\nBelfast\r\n"]},
{"city": ["\r\nCardiff\r\n"]},
{"city": ["\r\nNewcastle upon Tyne\r\n"]},
{"city": ["\r\nBournemouth\r\n"]},
{"city": ["\r\nWhitby\r\n"]},
{"city": ["\r\nLlandudno\r\n"]},
{"city": ["\r\nOxford\r\n"]},
{"city": ["\r\nBristol\r\n"]},
{"city": ["\r\nLeeds\r\n"]}
]

我需要获取每个城市并将其添加到我的列表中。到目前为止,这就是我所做的

import json

myList = []

with open('city.json') as json_data:
    data = json.load(json_data)
    for index in data:
       myList.append(index['city'])

for index in range(len(myList)):
   print (str(myList[index]).replace("[","").replace("]","").replace("\r\n",""))

我需要我的名单只包括[伦敦,爱丁堡,布莱克浦...]而不是像顶部看到的任何其他人物。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

每个字典中的每个值都是包含一个字符串的列表。拿第一个元素:

with open('city.json') as json_data:
    data = json.load(json_data)
    for index in data:
       myList.append(index['city'][0])  # note the indexing

您可能希望使用str.strip()删除每个城市值周围的\r\n空格:

with open('city.json') as json_data:
    data = json.load(json_data)
    for index in data:
       myList.append(index['city'][0].strip())

您可以将整个内容放入list comprehension,无需使用list.append()

with open('city.json') as json_data:
    data = json.load(json_data)
    myList = [d['city'][0].strip() for d in data]

演示,将您的JSON示例放入字符串json_data

>>> data = json.loads(json_data)
>>> [d['city'][0].strip() for d in data]
['London', 'Edinburgh', 'Blackpool', 'Brighton & Hove', 'Glasgow', 'Manchester', 'York', 'Torquay', 'Inverness', 'Liverpool', 'Birmingham', 'Bath', 'Scarborough', 'Cambridge', 'Newquay', 'Aberdeen', 'Belfast', 'Cardiff', 'Newcastle upon Tyne', 'Bournemouth', 'Whitby', 'Llandudno', 'Oxford', 'Bristol', 'Leeds']
>>> from pprint import pprint
>>> pprint(_)
['London',
 'Edinburgh',
 'Blackpool',
 'Brighton & Hove',
 'Glasgow',
 'Manchester',
 'York',
 'Torquay',
 'Inverness',
 'Liverpool',
 'Birmingham',
 'Bath',
 'Scarborough',
 'Cambridge',
 'Newquay',
 'Aberdeen',
 'Belfast',
 'Cardiff',
 'Newcastle upon Tyne',
 'Bournemouth',
 'Whitby',
 'Llandudno',
 'Oxford',
 'Bristol',
 'Leeds']