2017-06-21 65 views
0

我想访问的Python JSON对象,我通过不同的错误如何在python

这个运行访问JSON是数据

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 
+0

哪里是错误? –

+0

TypeError:字符串索引必须是整数,而不是str –

回答

0

使用json.loads把它转换成一个Python字典:

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

与您之前获取的错误是因为字符串对象应该用整数索引。

让我们完全不同的字符串,看看为什么:

'abcd'[0] # 'a' 
'abcd'['xyx'] # What does this even mean? TypeError! 
'{"0":{"created":"05-16-13","counter":3}"}'['couter'] # TypeError for the same reasons. 
+0

我赢了7秒。 ;) –

+0

我得到TypeError:元组索引必须是整数,而不是str –

+0

@AbidemiOni糟糕。一个python'dict.items'返回一个类似于键和信息的列表。我雾化了钥匙。现在修复。 – Artyer

0

还有就是你可以导入和JSON库在Python中使用。您可以看到Python 3 here的文档和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]) 
0

因为value是一个字符串。您应该解析其中的json以访问其元素:

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