我正在使用python创建应用程序。我发出HTTP请求并获得以下结果:
{
"companies": {
"company": [
{
"createDt": "2014-01-18T00:00:00+01:00",
"dbNazev": "sveatlo_s_r_o_",
"id": "1",
"licenseGroup": "null",
"nazev": "Sveatlo s.r.o.",
"show": "true",
"stavEnum": "ESTABLISHED",
"watchingChanges": "false"
},
{
"createDt": "2014-01-20T00:00:00+01:00",
"dbNazev": "hajocka",
"id": "2",
"licenseGroup": "null",
"nazev": "HájoÄka",
"show": "true",
"stavEnum": "ESTABLISHED",
"watchingChanges": "false"
}
]
}
}
然后我在for循环中处理数据。问题是响应也可能如下所示:
{
"companies": {
"company": {
"createDt": "2014-01-18T00:00:00+01:00",
"dbNazev": "sveatlo_s_r_o_",
"id": "1",
"licenseGroup": "null",
"nazev": "Sveatlo s.r.o.",
"show": "true",
"stavEnum": "ESTABLISHED",
"watchingChanges": "false"
}
}
}
目前我在每次请求之后检查它是否是数组,但我觉得这不是最好的方法。有人可以帮我找一个更好的解决方案吗?
感谢您的回答。
编辑:我无法更改服务器的响应
答案 0 :(得分:5)
规范化您正在分析的信息。这可以防止你不得不重复自己:
假设您的数据可能如下所示:
some_json_data = {"companies": {"foo": 1}}
或者像这样:
some_json_data = {"companies": [{"foo": 1}]}
因此,在解析json数据时,请执行以下操作:
i_expect_an_array = some_json_data['companies']
if not isinstance(i_expect_an_array, list):
i_expect_an_array = (i_expect_an_array,)
# Now, you can process the data as you normally would
不需要两个具有相似外观代码的独立块。
答案 1 :(得分:2)
将not list转换为list或tuple然后循环:
def make_list(item):
if not isinstance(item, (list, tuple)):
return [item]
return list(item)
for company in make_list(data['companies']['company']):
process_company(company)