python Json conversion issue

49 views Asked by At
                    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)+'}')

here is the error:

for key, val in jsonCont.items(): AttributeError: 'list' object has no attribute 'items'

1

There are 1 answers

0
Peter On

What is the format of the JSON? When you do json.loads(), if it reads it as a list, the ".items()" method will not work.

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

vs

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

I imagine you are receiving the first example. You may need to do a little validating/cleaning to make sure it's in the structure you are expecting.