簡體   English   中英

Python-將JSON元素追加到列表

[英]Python - appending JSON elements to a 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",""))

我只需要[倫敦,愛丁堡,布萊克浦...]組成列表,而不需要其他類似頂部的字符。 我怎么解決這個問題 ?

每個字典中的每個值都是一個包含一個字符串的列表。 只需考慮第一個元素:

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.append() ,而無需使用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']

暫無
暫無

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

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