Tried to access key from dictionary and facing an issue

Hi Guys,
I have a JSON response which is =
{
“columns”:[
{
“name”:“user_id”,
“type”:“java.lang.Integer”
},
{
“name”:“contact_type”,
“type”:“java.lang.String”
},
{
“name”:“contact_value”,
“type”:“java.lang.String”
}
],
“rows”:[
[
1,
“email”,
susan.richards@mailinator.com
],
[
3,
“email”,
jane.doe@mailinator.com
]
]
}

Created a dictionary and passed this json response. Then, when i try to get the “rows” key it says ,
TypeError: unicode indices must be integers

This is my code:
import json

ds = system.db.runNamedQuery(“FetchUsers”)
pds = system.dataset.toPyDataSet(ds)
jsonString = system.util.jsonEncode(pds)
#print(jsonString)
dump = json.dumps(jsonString)
res = json.loads(dump)
print(res[“rows”])

By the way, it works well in online python console.
please do needful.

with proper formatting:

{
   "columns":[
      {
         "name":"user_id",
         "type":"java.lang.Integer"
      },
      {
         "name":"contact_type",
         "type":"java.lang.String"
      },
      {
         "name":"contact_value",
         "type":"java.lang.String"
      }
   ],
   "rows":[
      [
         1,
         "email",
         "susan.richards@mailinator.com"
      ],
      [
         3,
         "email",
         "jane.doe@mailinator.com"
      ]
   ]
}

You’re mixing up two json processing libraries, and making them do the same thing twice.
json.dumps() is meant to convert a dict into its string representation, but here you’re passing it a string.
I’m not quite sure what’s happening with the json.loads() at this point, but it can’t be good ! It seems it’s returning a string as well, so when you’re trying to index it it doesn’t work.
Remove the dump = json.dumps(jsonString) line and pass your jsonString to loads and you should be able to index it properly.

But more importantly, what are you trying to do ? Where is that used ? I kind of feel there ought to be a better way than transforming a dataset into a pydataset, then into a jsonstring, then into a dict.

1 Like

My mistake,
It worked Thanks.
By the way am using this for Alarm pipeline to dynamically fetch user info from DB

You should configure rosters instead, and use those in the notification block.

But if you don’t want to do that, then I’d suggest something like this, supposing you only want the email addresses:

ds = system.db.runNamedQuery(“FetchUsers”)
pds = system.dataset.toPyDataSet(ds)
email_addresses = [row[contact_value] for row in pds if row['contact_type'] == "email"]

No need to bring json into this.

1 Like