如何使用带有嵌套列表和字典的Python遍历JSON文件

时间:2019-08-19 12:54:05

标签: python json

我正在尝试使用Python遍历JSON文件,并返回该对象的名称以及相关的模块。

现在,我基本上可以得到想要对索引进行硬编码的输出了。但是,这显然不是正确的方法(JSON文件的长度可能会有所不同)。

每当我尝试使用循环时,都会出现如下错误:

TypeError: string indices must be integers 

我的JSON文件如下:

{
    "name": "gaming_companies",
    "columns": [{
            "name": "publisher",
            "type": "string",
            "cleansing": ["clean_string"]
        },
        {
            "name": "genre",
            "type": "string",
            "cleansing": ["match_genre", "clean_string"]
        },
        {
            "name": "sales",
            "type": "int",
            "cleansing": []
        }
    ]
}

“正在运行”的我的Python代码如下:

import json as js

def cleansing(games_json):
      print (games_json['columns'][0]['name'] + " - cleansing:")
      [print(i) for i in games_json['columns'][0]['cleansing'] ]
      print (games_json['columns'][1]['name'] + " - cleansing:")
      [print(i) for i in games_json['columns'][1]['cleansing'] ]
      print (games_json['columns'][2]['name'] + " - cleansing:")
      [print(i) for i in games_json['columns'][2]['cleansing'] ]

with open(r'C:\Desktop\gamefolder\jsonfiles\games.json') as input_json:
  games_json = js.load(input_json)
  cleansing(games_json)

我要返回的输出是:

publisher
cleansing:
clean_string

genre
cleansing:
match_genre
clean_string

sales 
cleansing:

我试图像这样遍历它们:

      for x in games_json:
          for y in games_json['columns'][x]:
              print (y)

结果:

TypeError: list indices must be integers or slices, not str

games_json显示为字典。

列显示为词典列表。

每个对象的清理属性显示为列表。

我认为这是我的问题所在,但我无法克服障碍。

3 个答案:

答案 0 :(得分:1)

这可能是可行的解决方案之一,因为您想迭代数组的元素。

    const getInbox = () => {
    return new Promise((resolve, reject) => {
        imaps.connect(config).then(function (connection) {
            return connection.openBox('INBOX').then(function () {
                var searchCriteria = ['ALL'];
                var fetchOptions = {
                    bodies: ['HEADER', 'TEXT', ''],
                };
                return connection.search(searchCriteria, fetchOptions).then(async function (messages) {
                    let promises = messages.map(item=>{
                        return new Promise((resolve,reject)=>{
                            var all = _.find(item.parts, { "which": "" })
                            var id = item.attributes.uid;
                            var idHeader = "Imap-Id: " + id + "\r\n";
                            simpleParser(idHeader + all.body, (err, mail) => {
                                resolve(mail);
                            });
                        });
                    });
                    Promise.all(promises).then(data=>{
                        let d = data.filter(obj=>obj.me).map(obj=>{
                            return {
                                from:obj.from.value.map(obj=>obj.address).join(','),
                                to:obj.to.value.map(obj=>obj.address).join(','),
                                subject:obj.subject,
                                attachments:obj.attachments,
                                message_id:obj.messageId,
                                date:obj.date

                            }
                        });
                        resolve(d);
                    })
                });
            });
        });
    }); }

答案 1 :(得分:1)

您尝试的问题是将迭代器用作字符串。

x中的for y in games_json['columns'][x]:是一个迭代器对象,而不是字符串['name', 'cleansing']

您可以了解有关python迭代器here

的更多信息

根据情况-您可能希望将columns作为单独的列表进行迭代。

此代码应该有效

for item in f["columns"]:
    print(item["name"])
    print("cleansing:")
    print(item["cleansing"])

输出-

publisher
cleansing:
['clean_string']
genre
cleansing:
['match_genre', 'clean_string']
sales
cleansing:
[]

答案 2 :(得分:1)

x = """{
    "name": "gaming_companies",
    "columns": [{
            "name": "publisher",
            "type": "string",
            "cleansing": ["clean_string"]
        },
        {
            "name": "genre",
            "type": "string",
            "cleansing": ["match_genre", "clean_string"]
        },
        {
            "name": "sales",
            "type": "int",
            "cleansing": []
        }
    ]
}"""
x = json.loads(x)
for i in x['columns']:
    print(i['name'])
    print("cleansing:")
    for j in i["cleansing"]:
        print(j)
    print('\n')

输出

publisher
cleansing:
clean_string


genre
cleansing:
match_genre
clean_string


sales
cleansing:

with open(r'C:\Desktop\gamefolder\jsonfiles\games.json') as input_json:
    games_json = js.load(input_json)
    for i in games_json['columns']:
        print(i['name'])
        print("cleansing:")
        for j in i["cleansing"]:
            print(j)
        print('\n')