我可以读取JSON数据并打印数据,但出于某种原因,它是以unicode的形式读取它,所以我不能使用简单的点符号来获取数据。
test.py:
#!/usr/bin/env python
from __future__ import print_function # This script requires python >= 2.6
import json, os
myData = json.loads(open("test.json").read())
print( json.dumps(myData, indent=2) )
print( myData["3942948"] )
print( myData["3942948"][u'myType'] )
for accnt in myData:
print( " myName: %s myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) ) # TypeError: string indices must be integers
#print( " myName: %s myType: %s " % ( accnt.myName, accnt.myType ) ) # AttributeError: 'unicode' object has no attribute 'myName'
#print( " myName: %s myType: %s " % ( accnt['myName'], accnt['myType'] ) ) # TypeError: string indices must be integers
#print( " myName: %s myType: %s " % ( accnt["myName"], accnt["myType"] ) ) # TypeError: string indices must be integers
test.json:
{
"7190003": { "myName": "Infiniti" , "myType": "Cars" },
"3942948": { "myName": "Honda" , "myType": "Cars" }
}
运行它我得到:
> test.py
{
"3942948": {
"myType": "Cars",
"myName": "Honda"
},
"7190003": {
"myType": "Cars",
"myName": "Infiniti"
}
}
{u'myType': u'Cars', u'myName': u'Honda'}
Cars
Traceback (most recent call last):
File "test.py", line 10, in <module>
print( " myName: %s myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) )
TypeError: string indices must be integers
所以我的问题是如何读取它以使键不是unicode(更受欢迎)或者如何在unodeode中访问for循环中的键。
答案 0 :(得分:2)
您需要使用dict myData
而不是字符串accnt
:
for accnt in myData:
print( " myName: %s myType: %s " % ( myData[accnt][u'myName'], myData[accnt][u'myType'] ) )
您还可以使用values()
词典中的myData
功能:
for accnt in myData.values():
print( " myName: %s myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) )