[英]How to convert json to a list in Python?
我有一些代碼將 JSON 從 API 調用轉換為 Python 列表,如下所示:
import json as js
def flatten(listText):
def _flatten(item):
if isinstance(item, dict):
for value in item.values():
yield from _flatten(value)
else:
yield item
return [list(_flatten(d)) for d in listText]
jsonText = '[{"stationID":"ABCD123","obsTimeUtc":"ABCD123-ABCD123-ABCD123:ABCD123:ABCD123","obsTimeLocal":"ABCD123-ABCD123-ABCD123 ABCD123:ABCD123:ABCD123","neighborhood":"ABCD123","softwareType":"EasyWeatherV1.4.6","country":"AU","solarRadiation":0,"lon":0,"realtimeFrequency":null,"epoch":0,"lat":0,"uv":0,"winddir":0,"humidity":0,"qcStatus":0,"imperial":{"temp":0,"heatIndex":0,"dewpt":0,"windChill":0,"windSpeed":0,"windGust":0,"pressure":0,"precipRate":0,"precipTotal":0,"elev":0}}]'
listText = js.loads(jsonText)
print(flatten(listText))
這非常有效,但是 JSON 已經改變,所以字符串現在被包裹在 {"observations:} 中,如下所示:
{"observations":[{"stationID":"ABCD123","obsTimeUtc":"ABCD123-ABCD123-ABCD123:ABCD123:ABCD123","obsTimeLocal":"ABCD123-ABCD123-ABCD123 ABCD123:ABCD123:ABCD123","neighborhood":"ABCD123","softwareType":"EasyWeatherV1.4.6","country":"AU","solarRadiation":0,"lon":0,"realtimeFrequency":null,"epoch":0,"lat":0,"uv":0,"winddir":0,"humidity":0,"qcStatus":0,"imperial":{"temp":0,"heatIndex":0,"dewpt":0,"windChill":0,"windSpeed":0,"windGust":0,"pressure":0,"precipRate":0,"precipTotal":0,"elev":0}}]}
正因為如此,而不是返回這樣的列表:
[['ABCD123', 'ABCD123:ABCD123:ABCD123', 'ABCD123-ABCD123-ABCD123 ABCD123:ABCD123:ABCD123', 'ABCD123', 'EasyWeatherV1.4.6', 'AU', 0, 0, None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
它只是返回:
[['observations']]
如何更改代碼以使其適用於新的 Json 格式?
您需要做的就是選擇與observations
字段對應的值,如下所示:
listText = js.loads(jsonText)['observations']
這給出了您需要的 output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.