1

我可以读取 JSON 数据并打印数据,但由于某种原因,它以 unicode 格式读取,因此我无法使用简单的点表示法来获取数据。

测试.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           

所以我的问题是我如何读取它以使键不是 unicode(更喜欢),或者当它们是 unicode 时如何在 for 循环中访问键。

4

1 回答 1

2

您需要使用 dictmyData而不是 string 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 回答