1

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 ループでキーにアクセスする方法です。

4

1 に答える 1

2

myDatastring の代わりにdict を使用する必要がありますaccnt

for accnt in myData:
  print( " myName: %s  myType: %s " % ( myData[accnt][u'myName'], myData[accnt][u'myType'] ) )

dictでvalues()関数を使用することもできます。myData

for accnt in myData.values():
  print( " myName: %s  myType: %s " % ( accnt[u'myName'], accnt[u'myType'] ) )
于 2013-07-19T22:46:22.400 に答える