Tuesday, December 31, 2013

How I combined simple #Python list comprehension and JSON parsing

There are lots of very interesting things to discover in Python - especially if you've been working with Java or any other programming language for some time. For example this simple piece of code demonstrates how you can quite easily convert a list of of Strings of integers separated by comma - into a list of integers. What I particularly like about this small code is that it uses what Python developers refer to list comprehension.
string1 = "020783, 503553, 555204"
mylist = [int(n) for n in string1.split(',')]
>>>>>> mylist
>>> [020783, 503553, 555204]
Now, that piece of code was all I needed to get the API application I was working on to generate a nested list of integers. As it turns out, Python makes things really easy.
def parse_points(self, json_response):
        try:
            result = json.loads(json_response)
            if result.has_key('points'):
                the_points = result['points']['code']
                mylist = [int(n) for n in the_points.split(',')]
                return mylist 
            else:
                return result
        except ValueError, e:
            raise PlottingError('JSON Parsing Error: ' + e)
.... Further down the code, that returned value is eventually used to as an array of list:
     "waypoints":[020783,
                  503553,
                  555204]
This would not make much sense to a lot of people out there - that is deliberate because I don't want to show the code in full. Protecting the real code is vital here. However, the aim for this small code is to demonstrate how to parse a list of integers in string separated by comma. With time I will post a full blog with a complete working code on how this works.

No comments:

Related Posts with Thumbnails