0

I have the following json (I've stripped a lot of the data out for simplicity):

{u'_links': [{u'uri': u'http://url/polling/v1/c1b1a360-1c69-49e0-9114-f02e3697e3ea', u'rel': u'header', u'methods': [u'GET', u'POST', u'PUT', u'OPTIONS']}, {u'uri': u'http://url/polling/v1/c1b1a360-1c69-49e0-9114-f02e3697e3ea/stores', u'rel': u'self', u'methods': [u'GET', u'PUT', u'POST', u'DELETE', u'OPTIONS']}], u'data': [{u'status': u'C2001', u'stackTrace': None, u'receivedIdx': 53713, u'description': u'Staged', u'timeChanged': u'2017-07-12T07:00:11.949-0400', u'storeNbr': u'1280', u'_links': [{u'uri': u'http://url.com/polling/v1/c1b1a360-1c69-49e0-9114-f02e3697e3ea/stores/1280', u'rel': u'self', u'methods': [u'GET', u'POST', u'DELETE', u'OPTIONS']}

I'm trying to get the "timeChanged" and "description" fields out of it.

data = json.loads(result.read())
for status in data:
  print "[",status['timeChanged'],"]", status['description']

results in:

TypeError: string indices must be integers

What am I doing wrong?

Any help would be appreciated

3
  • That's not JSON you have. That's Python's dict representation. Commented Jul 12, 2017 at 17:08
  • I'm sorry, I'm very new with json and Python. The "json" is the string I get when I print out what was in "data". Commented Jul 12, 2017 at 17:10
  • That string you get when you print data is the string representation of a dict, which is what randomir is trying to tell you. In other words, data is a dict (which makes sense because you are deserializing a JSON object when you call json.loads.) Commented Jul 12, 2017 at 17:13

2 Answers 2

1

Let's say that data = json.loads(result.read()) gives you the following dict:

{"foo": "bar", "baz": 3}

What happens when you iterate over a dict like this?

for x in data:
    print x

You get this:

foo
baz

The for loop iterates over the keys of the dictionary. Hence your TypeError when you try to subindex with a string on a string. You want something like this:

for x in data:
   status = data[x]
   ...

Well, maybe. I am confused about your example data, but you should understand the principle now.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that gave me just what I needed. I needed to get the value from the "data" key, and they print the 'field' from that data key. In this case for x in data["data"] print x['timeChanged', x['description'] Thank you!
0

I needed to get the value from the "data" key, and then print the 'field' from that data key. In this case

for x in data["data"]:
   print x['timeChanged', x['description']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.