json資料解析

2021-08-15 07:32:21 字數 2192 閱讀 1972

# coding:utf-8

'鄭州市&output=json&ak=tuegdhcvwi6forqnlm0qmxxy9n0okoiq&callback=?'

# 在python中傳送請求

# windows+r 輸入cmd 回車開啟命令列工具 輸入pip install requests

# 輸入pip list 檢視已經安裝過的包

import requests

# python內建的包,json

import json

while

true:

print

'**************歡迎使用天氣查詢系統*****************'

# 輸入乙個要查詢的城市名稱

city = raw_input('請輸入要查詢的城市名稱(輸入q退出):')

if city == 'q':

break

# 1.準備url位址

url = '%s&output=json&ak=tuegdhcvwi6forqnlm0qmxxy9n0okoiq&callback=?'%city

# 2.傳送乙個get請求,獲取url位址下的資源內容

# get(url) 需要將url位址作為引數進行傳遞

# response 接受伺服器返回的響應資料

response = requests.get(url)

# 把json字串轉換python中的字典或列表

weather_dict = json.loads(response.content)

# 根據key取出字典中對應的值

date = weather_dict.get('date')

# 取出results列表

results = weather_dict['results']

# 取出results中的字典

detail_dict = results[0]

# 取出當前城市

current_city = detail_dict['currentcity']

print

u'當前城市:%s' % current_city

# 取出pm值

pm25 = detail_dict['pm25']

# 把取出的pm25字串轉換為數字,再進行比較

pm25 = int(pm25)

if pm25 <= 50:

print

'pm值%s,優' % pm25

elif pm25 <= 100:

print

'pm值%s,良' % pm25

elif pm25 <= 150:

print

'pm值%s,輕度汙染' % pm25

elif pm25 <= 200:

print

'pm值%s,中度汙染' % pm25

elif pm25 <= 300:

print

'pm值%s,重度汙染' % pm25

else:

print

'pm值%s,嚴重汙染' % pm25

# 取出指引列表

indexs = detail_dict['index']

# for迴圈遍歷index列表,取出小字典

for index in indexs:

title = index['title']

zs = index['zs']

tipt = index['tipt']

des = index['des']

print

# 取出天氣情況列表

weather_data = detail_dict['weather_data']

# for迴圈遍歷weather_data,取出小字典

for weather_dict in weather_data:

date = weather_dict['date']

weather = weather_dict['weather']

wind = weather_dict['wind']

temperature = weather_dict['temperature']

print

u'日期:%s 天氣:%s 風級:%s 溫度:%s'%(date,weather,wind,temperature)

json資料解析

由於是從網路上面讀取json,因此需要讀取網路檔案 url url new url path httpurlconnection conn httpurlconnection url.openconnection 利用httpurlconnection物件,我們可以從網路中獲取網頁資料.conn.s...

json資料解析

今天在做easyui列表頁面回顯字典表資料時候遇到乙個json解析的奇怪問題,首先我用spring gethibernatetemplate 中的createsqlquery進行資料查詢 查出來的資料是 2,2,2,2,2,2,2,之類的 public list findbypage final s...

Json 資料解析

假設現在要建立這樣乙個json文字 物件 married false 布林值 try 新建people物件 jsonarray phone new jsonarray phone是個陣列 phone.put 123231 put 1231234 把 號碼放到phone裡面 people.put ph...