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

Denis McMahon denismfmcmahon at gmail.com
Fri Jan 10 18:56:27 EST 2014


On Fri, 10 Jan 2014 12:57:59 -0800, vanommen.robert wrote:

> Hello,
> 
> I have a Raspberry Pi with 10 temperature sensors. I send the data from
> the sensors and some other values with json encoding and:
> 
> result = urllib2.urlopen(request, postData)
> 
> to a online PHP script wich places the data in a mysql database.
> 
> In the result:
> 
> result.read()
> 
> i am trying to send data back from the PHP to the RPI. I make an array
> in PHP
> 
> $para[0] = $REGELING_ORG;
> $para[1] = $VLVERWL_ORG;
> $para[2] = $VLOERVRAAG_ORG;
> $para[3] = $TIJDVLOER_ORG;
> $para[4] = $SETPOINT_ORG;
> 
> echo $para;

This is php code that prints out a string representation of the variable, 
in so far as it can.

What you probably want to do is encode the array somehow, such as one 
element value per line, or json encode, or some other method, and then 
decode it in your python.

> In python when i do
> 
> para = result.read()
> print para
> 
> the output is:
> 
> [null,null,null,null,null,"J"]

Yep, that's because para is a string containing the text:

'[null,null,null,null,null,"J"]'

> This is correct according to the data in PHP from the mysql.
> 
> when I do
> 
> print para[1]
> 
> the output is:
> 
> n
> 
> the seccond character from the data. Why is this not the seccond
> datafield?
> And why is para[5] not "J" but ,   ?

This is because python is looking at a string containing the character 
sequence '[null,null,null,null,null,"J"]'

para[0] = '['
para[1] = 'n'
para[2] = 'u'
para[3] = 'l'
para[4] = 'l'
para[5] = ','
para[6] = 'n'
para[7] = 'u'

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

To use json to convert it back to an array in the python code, you also 
need to use json to serialise the array in the php code.

eg in the php:

echo $para;

would become:

echo php_json_encoding_function( para );

and in the python:

para = result.read()

would become:

para = python_json_decoding_function( result.read() )

or possibly even:

para = json.decode( result.read() )

(I don't know the details, I'm trying to give you the general idea so you 
can work out where to look to figure this out)

These two web pages may also help:

http://uk3.php.net/manual/en/function.json-encode.php
http://docs.python.org/2/library/json.html

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list