首页 > 解决方案 > python Json转换问题

问题描述

                    if not server in finalOp.keys():
                            #pdb.set_trace()
                            finalOp[server] = []
                            req = Request('http://localhost:80/status.json')
                            res = urlopen(req)
                            jsonCont = json.loads(str(res.read().decode()))  
                            for key, val in jsonCont.items():
                                  if type(val) is list:
                                          val = ''.join(val)
                                  content.append(key+''+val)
                            #format {'server': [{content}]
                            finalOp[server].append('{'+','.join(content)+'}')

            except URLError as e:
                    #Assgining NA when URL not reachable or request not fulfilled
                    content = ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']
                    finalOp[server].append('{'+','.join(content)+'}')

这是错误:

jsonCont.items() 中的键、val:AttributeError:“list”对象没有属性“items”

标签: pythonjsontype-conversion

解决方案


JSON的格式是什么?当您执行 json.loads() 时,如果它以列表的形式读取它,“.items()”方法将不起作用。

json.loads('[{"name": "John", "age": 31, "city": "New York"}]').items()

对比

json.loads('{"name": "John", "age": 31, "city": "New York"}').items()

我想你正在收到第一个例子。您可能需要做一些验证/清理以确保它在您期望的结构中。


推荐阅读