kemosabee kemosabee - 3 months ago 8
PHP Question

how to avoid typeerror while returning result from php to python

I have the following code in php and python,I return $result from php to a python handler and running into below error..how should I return in python so that I don't run into this error?

php

$result = [
"TRIGGER_STATUS" => "SUCCESS",
"PW_LINK" => "https://pw.company.com/"
];


Python

orderedResults = sorted(result['result'].items(), key=lambda kv: kv[1]['Order'])


Error:-

File "\\data\workspace\username\pwp4plugin\UI.py", line 269, i
n <lambda>
orderedResults = sorted(result['result'].items(), key=lambda kv: kv[1]['Orde
r'])
TypeError: string indices must be integers, not str

Answer

The issue is with kv[1]['Order'] being passed to the lambda function being passed to key. Assuming the dict which Python has after doing json.decode() is this:

>>> result = {'result': {
...                      "TRIGGER_STATUS": "SUCCESS",
...                      "PW_LINK": "https://pw.company.com/"
...                      }
...           }
>>>
>>> # this is what .items() looks like:
... result['result'].items()
[('PW_LINK', 'https://pw.company.com/'), ('TRIGGER_STATUS', 'SUCCESS')]

So in the loop, index 1 is 'https://pw.company.com/' and 'SUCCESS':

>>> for kv in result['result'].items():
...   print kv[1]
...
https://pw.company.com/
SUCCESS
  1. So kv[1]['Order'] is attempting to lookup a key called 'Order' against each of the two strings. Whereas, what Python is expecting is an integer index to something in each of those strings. Example:

    >>> for kv in result['result'].items():
    ...   print kv[1][4]  # the fifth letter in each string
    ...
    s
    E
    
  2. In the PHP associative array you've given, there is no key 'Order'. So it's unclear to us what you were trying to use. What is result in Python once the PHP result is parsed?