python - 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”
解决方案
JSON的格式是什么?当您执行 json.loads() 时,如果它以列表的形式读取它,“.items()”方法将不起作用。
json.loads('[{"name": "John", "age": 31, "city": "New York"}]').items()
对比
json.loads('{"name": "John", "age": 31, "city": "New York"}').items()
我想你正在收到第一个例子。您可能需要做一些验证/清理以确保它在您期望的结构中。
推荐阅读
- amazon-web-services - 更新堆栈时使用现有的 DBUser 和 DBPassword 参数值
- cross-validation - 如何在 k-fold CV 设置中组织 Ray Tune Trainable 类计算?
- tensorflow - TensorFlow - 在 TF1.14 中,我如何将 RaggedTensor 变成张量或如何填充它?
- azure - Azure 数据工厂 - 启用 git n azure 数据工厂时,触发器不起作用
- angular - 无法绑定到 Angular 9 自定义指令
- java - 后台线程中的进度条.setProgress(variable)
- snakemake - 从配置文件传递通配符约束字典
- python - ID不同时的Web Scraping产品
- ios - 将变量从 ViewController 传递回前一个,但变量没有更新?
- swift - UITableView Swift 所需的设计建议