Abidemi Oni
Abidemi Oni

Reputation: 25

How to access json in python

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

Upvotes: 1

Views: 2664

Answers (3)

Artyer
Artyer

Reputation: 40791

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.

Upvotes: 2

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14096

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']

Upvotes: 0

Marcus Lind
Marcus Lind

Reputation: 11440

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])

Upvotes: 0

Related Questions