我如何使用python

时间:2016-11-25 18:36:13

标签: python json

我正在阅读的json文件看起来像这样,我决定不发布实际文件,因为它是一个类项目,并且不觉得发布它感觉很舒服(它是validated):

{ "peoples": [ 
 {blah1 : blah, blah2: blah,blah3 : blah, blah4: blah,blah5 : blah, 
 blah6:blah,blah7 : blah, blah8: blah,blah9 : blah, blah10: blah,}

 {blah1 : blah, blah2: blah,blah3 : blah, blah4: blah,blah5 : blah, 
 blah6:blah,blah7 : blah, blah8: blah,blah9 : blah, blah10: blah,} 
 ]
 }
到目前为止,我在python上的代码看起来像这样,我不完全确定这是编码这种情况的最佳方法,但它确实有效,为什么我要求帮助:

import simplejson  

class People(dict):
   def __init__(self):
    self.tricks = []
    _keys = ['blah1', 'blah2', 'blah3','blah4', 'blah5', 'blah6','blah7', 
      'blah8','blah9','blah10']


   def getJSONdata(self,tricks):
       with open(Dfile.json, 'r') as peopleData:
           dataObject = simplejson.load(peopleData)
           for people in dataObject['peoples']:
               return (people[tricks])

 peep = People()
 peep1 = People()

 print(peep.getJSONdata("blah1"))
 print(peep1.getJSONdata("blah2"))  

我可以使用键访问对象上的任何内容,但无法访问第二个等等...我已查看了多个json和python站点,并没有真正解决此问题。任何帮助,将不胜感激。

我希望能够平等地访问这些对象。所以我可以从object1,object2等获得blah1。

1 个答案:

答案 0 :(得分:0)

我认为您的设置对于您想要做的事情来说有点过分。

让我们说你的JSON文件如下所示:

{"peoples": [
     {"blah8": "blah", "blah2": "blah", "blah4": "blah", "blah3": "blah", "blah9": "blah", "blah7": "blah", "blah1": "blah", "blah6": "blah", "blah5": "blah", "blah10": "blah"}, 
     {"blah8": "blah", "blah2": "blah", "blah4": "blah", "blah3": "blah", "blah9": "blah", "blah7": "blah", "blah1": "blah", "blah6": "blah", "blah5": "blah", "blah10": "blah"}
]}

peoples中的每个对象都应该代表一个人。使用json,您可以将JSON文件中的数据加载到Python字典中:

import json

dataObject = json.load(open("myjsonfile.json", "r"))

然后,dataObject['peoples']是一群人。 dataObject['peoples'][0]是第一个人。 dataObject['peoples'][1]是第二个人,依此类推。

现在,如果你想迭代每个人并获得给定密钥的值:

key = "blah2"
for p in dataObject['peoples']:
    print(p.get("blah2", None))

将打印" blah2"每个人的关键。如果找不到密钥,则返回None。这只是一种安全,以防你最终得到一个没有特定密钥的人。所以这里的输出应该是:

blah
blah

总的来说,创建一个对象是没有必要的。您可以通过简单地加载json数据然后使用函数来实现此功能:

import json

dataObject = json.load(open("myjsonfile.json", "r"))

def getDataFromPersons(key, persons):
   # build a list of the values from each person with the given key
   return [p.get(key, None) for p in persons]

d = getDataFromPersons("blah2", data['persons'])
print(d)
# blah
# blah

但是,您可能希望能够跟踪数据来自哪个人。在这种情况下,您需要构建字典而不是列表:

def getDataFromPersons(key, persons):
   # build a dictionary where the key is the index of the person in the list
   # and the value is the value for that person at the given key
   return {i:p.get(key, None) for i,p in enumerate(persons)}

这会输出{0: 'blah', 1: 'blah'}