tafazzi87 tafazzi87 - 4 months ago 30
JSON Question

type error while parsing json output python

i'm trying to parse some fields of a json, that is an output for a command line. but i can't access to any field, i've always this error :

TypeError: 'int' object has no attribute '__getitem__'


my json output is like this :

{"result":"success","totalresults":"1","startnumber":0,"numreturned":1,"tickets":{
"ticket":[
{
"id":"2440",
"tid":"473970",
"deptid":"1",
"userid":"0",
"name":"John",
"email":"email@email.it",
"cc":"","c":"P1gqiLym",
"date":"2016-07-01 13:00:02",
"subject":"test",
"status":"stato",
"priority":"Medium",
"admin":"",
"attachment":"image001.jpg",
"lastreply":"",
"flag":"0",
"service":""
}
]
}
}


and my code is this :

import json
import sys
import subprocess

output=subprocess.call('pywhmcs --url http://whmcs.test.it --username myuser --password mypass --action gettickets --params status="tickets" email="email@email.com"',shell=True)
values = json.loads(str(output))
print (values['result'])


why i can't access to any fields? maybe i cannot parse this type of subprocess output?

thanks guys

Answer

The problem is that subprocess.call returns the resultcode of the execution; which is either 0 (if successful) or any other positive integer if there is an error condition.

Now, when you execute output['result'], it is the same as doing 0['result'] which doesn't make sense as numbers don't support fetching by [], the technical term for that is __getitem__.

You need to execute subprocess.check_output; which returns the output as a string.

Then you have another minor issue that you need to fetch the dictionary on the resulting parsed json, and not output.

In short, you need:

import json
# import sys -- not required
import subprocess

output=subprocess.check_output('pywhmcs --url http://whmcs.test.it --username myuser --password mypass --action gettickets --params status="tickets" email="email@email.com"',shell=True)
values = json.loads(str(output))
print (values['result']) # note values, not output
Comments