1

I am trying to access json object in python and I am running through different errors

this is the data

value =    '{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}'

I will like to get 
"05-16-13","counter":3
"05-18-13","counter":1
I did

for info in value:
     print info['counter']

I keep getting a type error, any help?
TypeError: string indices must be integers, not str
2
  • where is the error ? Commented Jun 21, 2017 at 9:24
  • TypeError: string indices must be integers, not str Commented Jun 21, 2017 at 9:25

3 Answers 3

2

Use json.loads to convert it into a Python dictionary:

import json

value = '{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}'

d = json.loads(value)

for key, info in d.items():
    print info['counter']

The error you were getting before was because string objects should be indexed by integers.

Let's take a completely different string and see why:

'abcd'[0]  # 'a'
'abcd'['xyx']  # What does this even mean? TypeError!
'{"0":{"created":"05-16-13","counter":3}"}'['couter']  # TypeError for the same reasons.
Sign up to request clarification or add additional context in comments.

3 Comments

I win by 7 seconds. ;)
I get TypeError: tuple indices must be integers, not str
@AbidemiOni Oops. A python dict.items returns a list-like of the key and info. I fogot the key. Fixed now.
0

There is a json library that you can import and use in Python. You can see docs for Python 3 here and Docs for Python 2 here.

import json

value = '{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}'

value = json.loads(value)
print(value[0])

Comments

0

Because value is a string. You should parse the json in it to access to its elements:

import json
value = json.loads('{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}')

for info in value.items():
    print info['counter']

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.