Json fipy afer urequest



  • Hello,
    I wish you to enjoy the Christmas holiday.

    I'm coming to you because I can't get them back to you because I wish I could. I do a get on api that returns a JSON object with objects inside. I would like to retrieve the data and store it but the conversion doesn't work. Do you have an idea?

    Thanks ! :)
    abdfbb36-38a0-460d-a94c-9562f482ef0a-image.png
    f164d152-e141-4fb1-af07-417bb7fe98f0-image.png



  • @Tgasser

    r does nor contain valid JSON,

    The valid part is surrounded by ?()
    If you cannot fix the web service, you have to remove the invalid part before using it as a parameter



  • Thank you for your help and Happy New Year.
    It's all code this time and well formatted.

    from network import LTE
    from machine import Timer
    import time
    import sys
    import machine
    from machine import Pin
    
    import usocket
    import urequest
    
    from network import Bluetooth
    from network import LTE
    import ubinascii
    
    import time
    import sys
    import machine
    from machine import Pin
    
    import usocket
    import urequest
    
    from network import Bluetooth
    
    from machine import SPI, Pin
    from ssd1306 import SSD1306_SPI as ssd
    
    import utime
    import pycom
    import json
    import ujson
    
    
    pycom.heartbeat(False)
    
    lte = LTE()
    lte.init()
    rtc= machine.RTC()
    
    def connect_to_LTE():
    
       lte.send_at_cmd('AT+CMEE=2')
       lte.send_at_cmd('AT+CREG?')
    
       lte.attach(band=8,apn="iot.1nce.net")
       lte.send_at_cmd('AT+COPS=1,2,"26201",9')
       lte.send_at_cmd('AT+CEREG=2')
       #lte.send_at_cmd('AT+CGDCONT=0')
       i=0
       while not lte.isattached():
           time.sleep(0.5)
           print(".", end="")
           i=i+1
           if i%3 == 0:
               print(lte.send_at_cmd('AT+COPS=1,2,"26201",9'))
               print(lte.send_at_cmd('AT+CSQ'))
    
       print("\nAttached!")
    
       print(lte.send_at_cmd("AT+CSQ"))
    
       lte.connect()       # start a data session and obtain an IP address
       while not lte.isconnected():
           time.sleep(0.5)
           print("-", end="")
       print("Connected!")
       pycom.rgbled(0xd5362a) # red
    
    def request():
       print("DSN :")
       print(usocket.dnsserver())
       usocket.dnsserver(0, '8.8.8.8')
       usocket.dnsserver(1, '10.0.0.1')
       print(usocket.dnsserver())
       flag=False
       while(flag==False):
           try :
               print("Using library urequest...")
               r= urequest.get("http://api.open-notify.org/iss-now.json?callback=?")
               print("Return:", r.text) #r.content
               flag=True
               pycom.rgbled(0x7ed446) # green
               return r
           except OSError as err:
               print("OUPS ! OS Error {0}".format(err))
    
    def deconnect_to_LTE():
       try :
           pycom.rgbled(0xd5362a) # red
           lte.disconnect()
           print("Disconnected!")
           lte.detach()
           print("Dettached!")
           lte.deinit()
       except OSError as err:
           print('Oups..')
    
    def timestamp():
       print(rtc.ntp_sync("0.pool.ntp.org") ) # printing None
       timestamp = utime.localtime(utime.time()) #printing (2000, 1, 1, 0, 20, 16, 5, 1) but i would like to have  (2019, 12, 24, 12, 36, xx, xx, xx)
       print(timestamp)
       return timestamp
    
    def is_known():
       flag=-1
       for i in range(0, device_found):
           check=ubinascii.hexlify(adv.mac)
           if (check == list_device[i][1]):
               flag = i
       return flag
    
    def is_flower_care():
       name=bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)
       if(name == 'Flower care'):
           print(name)
           return True
       else:
           return False
    
    check_time = 60 #second
    list_device = []
    device_found = 0
    
    spi = SPI(0, SPI.MASTER, baudrate=100000, polarity=0, phase=0)
    disp = ssd(128,64,spi,Pin('P9'),Pin('P8'),Pin('P22'))
    disp.text('I\'m ready',0,0)
    disp.show()
    
    connect_to_LTE()
    r=request()
    deconnect_to_LTE()
    
    print(json.loads(r.text)) #line 134
    

    079a6e6c-3379-45df-a6ae-54ea92091979-image.png



  • Dear @Tgasser,

    the code you are showing should grok with the NameError: name 'json' isn't defined error again.

    You have to look at the library I've linked to and here's my full code if it helps.

    I don't see that error coming from the urequests module. At least, you didn't show any Python traceback indicating so.

    AttributeError: 'str' object has no attribute 'json'

    is even more strange to me.

    Are you sure you are running only this code on the device?

    With kind regards,
    Andreas.



  • @Tgasser please give matching source and errors/logs, and correctly format source code by putting ``` alone one a line before and after your code.

    As it stands, line numbering of the errors and your code don’t quite seem to match.



  • @andreas You have to look at the library I've linked to and here's my full code if it helps. Thanks :)

    lte = LTE()
    lte.init()
    rtc= machine.RTC()
    
    def connect_to_LTE():
    
        lte.send_at_cmd('AT+CMEE=2')
        lte.send_at_cmd('AT+CREG?')
    
        lte.attach(band=8,apn="iot.1nce.net")
        lte.send_at_cmd('AT+COPS=1,2,"26201",9')
        lte.send_at_cmd('AT+CEREG=2')
        #lte.send_at_cmd('AT+CGDCONT=0')
        i=0
        while not lte.isattached():
            time.sleep(0.5)
            print(".", end="")
            i=i+1
            if i%3 == 0:
                print(lte.send_at_cmd('AT+COPS=1,2,"26201",9'))
                print(lte.send_at_cmd('AT+CSQ'))
    
        print("\nAttached!")
    
        print(lte.send_at_cmd("AT+CSQ"))
    
        lte.connect()       # start a data session and obtain an IP address
        while not lte.isconnected():
            time.sleep(0.5)
            print("-", end="")
        print("Connected!")
        pycom.rgbled(0xd5362a) # red
    
    def request():
        print("DSN :")
        print(usocket.dnsserver())
        usocket.dnsserver(0, '8.8.8.8')
        usocket.dnsserver(1, '10.0.0.1')
        print(usocket.dnsserver())
        flag=False
        while(flag==False):
            try :
                print("Using library urequest...")
                r= urequest.get("http://api.open-notify.org/iss-now.json?callback=?")
                print("Return:", r.text) #r.content
                flag=True
                pycom.rgbled(0x7ed446) # green
                return r
            except OSError as err:
                print("OUPS ! OS Error {0}".format(err))
    
    def deconnect_to_LTE():
        try :
            pycom.rgbled(0xd5362a) # red
            lte.disconnect()
            print("Disconnected!")
            lte.detach()
            print("Dettached!")
            lte.deinit()
        except OSError as err:
            print('Oups..')
    
    connect_to_LTE()
    r=request()
    deconnect_to_LTE()
    
    print(json.loads(r))
    


  • This looks like a programming error on line 77 within your main.py. Without seeing the code, there's no way to reason about the error.



  • @andreas Sorry, I made a mistake with the picture, this is the correct screenshot : 479bfb79-7374-4990-bed7-c29d4fc53eeb-image.png

    the lib use is https://github.com/micropython/micropython-lib/blob/master/urequests/urequests.py

    Thank you for your help.



  • Dear @Tgasser,

    line 133 obviously needs an import json statement in order to be able to invoke the loads function on the module level.

    With kind regards,
    Andreas.


Log in to reply
 

Pycom on Twitter