简体   繁体   English

我如何使用python迭代json对象

[英]how do i iterate through json objects using python

The json file I'm reading from looks like this, I decided to not to post the actual file since it's for a class project and don't feel comfortable posting that(it is validated ): 我正在阅读的json文件看起来像这样,我决定不发布实际文件,因为它是一个类项目,并且感觉不舒服发布(它已经过验证 ):

{ "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,} 
 ]
 }

My Code on python looks like this so far, I'm not entirely sure that this is the best way to code for this situation but it does work partially and why I'm asking for assistance: 到目前为止,我的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"))  

I can access anything on the object using keys but can't access the second, etc... I have looked through multiple json and python sites and nothing really addresses this issue. 我可以使用键访问对象上的任何内容,但无法访问第二个等等...我已查看了多个json和python站点,没有真正解决此问题。 Any help would be appreciated. 任何帮助,将不胜感激。

I'd like to be able to access the objects equally. 我希望能够平等地访问这些对象。 so i could get blah1 from object1, object2 etc.. 所以我可以从object1,object2等获得blah1。

I think your setup is a little overkill for what you want to do. 我认为您的设置对于您想要做的事情来说有点过分。

Let's say your JSON file looks like this: 假设您的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"}
]}

Each object in peoples is supposed to represent a person. peoples每个对象都应该代表一个人。 Using json you can load the data from your JSON file into a Python dictionary: 使用json您可以将JSON文件中的数据加载到Python字典中:

import json

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

Then, dataObject['peoples'] is the array of people. 然后, dataObject['peoples']是人的数组。 dataObject['peoples'][0] is the first person. dataObject['peoples'][0]是第一个人。 dataObject['peoples'][1] is the second person and so on. dataObject['peoples'][1]是第二人,依此类推。

So now if you want to iterate through the each person and get the value for a given key: 所以现在如果你想迭代每个人并获得给定键的值:

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

Which will print the "blah2" key for each person. 这将打印每个人的“blah2”键。 If the key is not found, then it will return None. 如果找不到密钥,则返回None。 This is simply a safety in case you end up with a person who doesn't have a particular key. 如果你最终得到一个没有特定钥匙的人,这只是一种安全。 So the output here should be: 所以这里的输出应该是:

blah
blah

Overall, creating an object is not necessary. 总的来说,创建一个对象是没有必要的。 You can achieve this functionality by simply loading the json data and then using a function: 您只需加载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

However, you likely want to be able to keep track of which person the data came from. 但是,您可能希望能够跟踪数据来自哪个人。 In that case you'd want to build a dictionary instead of a list: 在这种情况下,您需要构建字典而不是列表:

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

This would output {0: 'blah', 1: 'blah'} . 这将输出{0: 'blah', 1: 'blah'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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