有b站的小伙伴问了我这个问题,在用requests请求的时候无法正确解析json内容,我查了一部分资料,主要是返回的数据被压缩过了,无法正常解码,所以要先解压再解码就好了,上代码参考:

import uzlib as zlib
import network,time,ujson
import urequests
FTEXT    = 1
FHCRC    = 2
FEXTRA   = 4
FNAME    = 8
FCOMMENT = 16

def decompress(data):
    assert data[0] == 0x1f and data[1] == 0x8b
    assert data[2] == 8
    flg = data[3]
    assert flg & 0xe0 == 0
    i = 10
    if flg & FEXTRA:
        i += data[11] << 8 + data[10] + 2
    if flg & FNAME:
        while data[i]:
            i += 1
        i += 1
    if flg & FCOMMENT:
        while data[i]:
            i += 1
        i += 1
    if flg & FHCRC:
        i += 2
    return zlib.decompress(memoryview(data)[i:], -15)

def WIFI_Connect():
    wlan = network.WLAN(network.STA_IF) 
    wlan.active(True)                   
    start_time=time.time()              
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('hideonbush', '800080008000') 
        while not wlan.isconnected():
            if time.time()-start_time > 15 :
                print('WIFI Connected Timeout!')
                break

    if wlan.isconnected():
        print('network information:', wlan.ifconfig())
        
WIFI_Connect()

url='https://devapi.qweather.com/v7/air/now?location=101060604&key=53c072543ef54ef591a3076adde9bd68'
res=urequests.get(url)
data=decompress(res.content).decode()
dic=ujson.loads(data)
print(dic)
print(dic['code'])
print(res.content)

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐