[Solved] Python - Dictionary?



  • I am stuck - supposedly this line (given from ubus -S call gps info written to a file) is in the correct format to be considered a "dictionary object" by python. Is there something else I should be using?

    {"age":6357,"latitude":"38.1234","longitude":"-80.1234","elevation":"1234.5","course":"12.34","speed":"N"}

    However, when I try and read out the data with the following script:
    #!/usr/bin/env python

    gpsfile=open('/root/gpsinfo.txt', 'r')
    gpsinfo=gpsfile.read()

    age=gpsinfo['age']
    lat=gpsinfo['latitude']
    lon=gpsinfo['longitude']
    elv=gpsinfo['elevation']
    cou=gpsinfo['course']
    spd=gpsinfo['speed']

    print "Age: "+age
    print "Latitude: "+lat
    print "Latitude: "+lon
    print "Longitude: "+elv
    print "Course: "+cou
    print "Speed: "+spd

    exit()

    I just get the following error:
    Traceback (most recent call last):
    File "test.py", line 10, in <module>
    age=gpsinfo['age']
    TypeError: string indices must be integers, not str



  • gpsfile=open('/root/gpsinfo.txt', 'r')
    gpsinfo=gpsfile.read()
    

    read() method returns string here, as you are simply reading a file.

    If this is the actual data from the file, with double quotes around key names and values:

    {"age":6357,"latitude":"38.1234","longitude":"-80.1234","elevation":"1234.5","course":"12.34","speed":"N"}
    

    Then you can use json to load it up. This should work:

    #!/usr/bin/env python
    import json
    
    from pprint import pprint
    
    
    with file('/root/gpsinfo.txt', 'r') as gpsfile:
        gpsinfo = json.load(gpsfile)
    
    age = gpsinfo['age']
    lat = gpsinfo['latitude']
    lon = gpsinfo['longitude']
    elv = gpsinfo['elevation']
    cou = gpsinfo['course']
    spd = gpsinfo['speed']
    
    pprint(("Age: " + age,
            "Latitude: " + lat,
            "Latitude: " + lon,
            "Longitude: " + elv,
            "Course: " + cou,
            "Speed: " + spd))
    
    exit()
    


  • Thank you, thank you, thank you! I have been spinning my wheels for hours now. That works, and I have incorporated it into my actual script.

    May even throw it up as a project!



  • @Brad-Buskey Your welcome. :) And share your projects!

    P.S. fixed a typo in my code sample.



  • This post is deleted!