我可以读取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(更受欢迎),或者当它们是unicode时,如何在for循环中访问它们。

最佳答案

您需要使用字典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'] ) )

10-07 14:05
查看更多