I’m trying to parse a json response object to get the hashID (objectiveHash) for each record, but I’m running into an error.
This is the error.
TypeError: string indices must be integers
Here is a snippit of the response.JSON for reference:
{
"Response": {
"records": {
"data": {
"featuredRecordHashes": [
3241995275,
3623956709,
1257350901
],
"records": {
"18302305": {
"state": 0,
"objectives": [
{
"objectiveHash": 836033085,
"progress": 1,
"completionValue": 1,
"complete": true,
"visible": true
}
],
"intervalsRedeemedCount": 0
},
"100144154": {
"state": 4,
"objectives": [
{
"objectiveHash": 3797031509,
"progress": 89,
"completionValue": 100,
"complete": false,
"visible": true
}
],
"intervalsRedeemedCount": 0,
"rewardVisibilty": [
true,
true
]
}
...
This is the relevant code.
json_response = response.json()
for record in json_response['Response']['records']['data']['records']:
myRecord = record['objectives']
for tst in myRecord:
hashID = str(tst['objectiveHash'])
Based on some research, the issue seems to be that myRecords variable is being taken as a string as opposed to an object or list. So, when I try to parse it, I get the error because you can’t parse a string. I’m not sure how to go about getting that value as a parseable object.
2
Answers
Your for loop is getting the keys assigned to record variable. records is a dictionary and iterating over a dictionary normally gets you the keys.
If you want the values then add .values() to the end of the json_response[‘Response’][‘records’][‘data’][‘records’] line.
If you want to have both the key and value then modify the code to have this:
TL;DR
If you iter through a nested dict-object, you will get the keys, not the sub-dicts.
Problem
For
record
applies, you want……but you get…
Solution 1
Always refer to your data dict:
Solution 2
Copy the sub-dict (or rather create a pointer internally):
Efficiency
Because they both refer to an address, they are equally efficient.
Proof: