简体   繁体   中英

Trouble accessing JSON data in Python for loop

I can read in the JSON data and print data but for some reason it is reading it in as unicode so I cannot use the simple dot notation to get at the data.

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" }
}

Running it I get:

> 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           

So my question is how do I read it in so that the keys are not unicode (much prefered) or how do access the keys in a for loop when they are unicode.

You need to use the dict myData instead of the string accnt :

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

You can also use the values() function on the myData dict:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM