【问题标题】:python Json conversion issuepython Json转换问题
【发布时间】:2020-03-12 18:40:55
【问题描述】:
                    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' object has no attribute 'items'

【问题讨论】:

  • 您能否提供 json 的 sn-p 以便我们了解您要完成的工作?
  • 这里是 json 文件 [{ "Application": "WebApp01", "Version": "1.0.1", "Uptime": "{{integer(1000, 100000)}}", "Request_Count": "{{integer(1000, 100000 * 5)}}", "Error_Count": "{{integer(1000, 4000 * 2)}}", "Success_Count": "{{integer(1000, 80000) * 2)}}" }]

标签: python json type-conversion


【解决方案1】:

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

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

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

我想您收到的是第一个示例。您可能需要进行一些验证/清理以确保它在您期望的结构中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2016-08-19
    • 2013-03-09
    • 2020-08-06
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多