无法在Python for循环中访问JSON数据

时间:2013-07-19 22:38:14

标签: python json python-2.7

我可以读取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循环中的键。

1 个答案:

答案 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'] ) )
相关问题