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
テスト.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
したがって、私の質問は、キーがユニコードにならないようにどのように読み込むか (はるかに好ましい)、またはキーがユニコードの場合に for ループでキーにアクセスする方法です。