Send array back in result from urllib2.urlopen(request, postData)

John Gordon gordon at panix.com
Fri Jan 10 17:53:19 EST 2014


In <aae37903-e5ab-41c5-87a7-2e3e78444878 at googlegroups.com> vanommen.robert at gmail.com writes:

> result = urllib2.urlopen(request, postData)

> para = result.read()
> print para

> the output is:

> [null,null,null,null,null,"J"]

> print para[1]

> the output is:

> n

Probably because para is a string with the value
'[null,null,null,null,null,"J"]'

> How can I change the data back to an array? I've tried with json, but
> that doesn't change anything.

As far as I know, result.read() only returns text.  If you want your results
in some other format (like an array), you'll need to parse the string.

This is a very simple (and ugly) way to do it, but it may give you a
starting point:

    # open the url
    result = urllib2.urlopen(request, postData)

    # read the raw text results
    raw_text = result.read()

    # strip off the leading '[' and trailing ']'
    raw_text = raw_text[1:-1]

    # split raw_text into an array of strings 
    text_array = raw_text.split(',')

    # declare a new list for storing the parsed items
    para = []

    # process each string
    for item in text_array:
        if item == 'null':
            para.append(None)
        else:
            para.append(item)

The python csv module might have a better way to do this; have a look.

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list