Reputation: 2257
New to python and I am trying to write a script to parse a json file to only print out the id and state of any of the values where the state is not "STARTED" and exit code 2. And print nothing if they all say STARTED and exit 0.
However, I am getting the error "string indices must be integers" Any suggestions on an issue with how I am trying to read this json?
import json
jsonFile = open('topics.json', 'r')
data = json.load(jsonFile)
for check in data['rows']:
if check['state'] is not "STARTED":
print check['id']['state']
and here is an example of my topics.json
{
"page": 0,
"page_size": 100,
"total_pages": 10,
"total_rows": 929,
"headers": [
"*"
],
"rows": [
{
"id": "168",
"state": "STARTED"
},
{
"id": "169",
"state": "FAILED"
},
{
"id": "170",
"state": "STARTED"
}
]
}
Upvotes: 0
Views: 913
Reputation: 177610
You want print check['id'],check['state']
.
check['id']
returns a string, so check['id']['state']
tries to index the string with a string, instead of an integer, resulting in the error.
Also, comparisons of inequality should use !=
not is not
. is
compares object identity, and two objects can have the same value and not be the same object, so use:
if check['state'] != "STARTED":
Upvotes: 5