【发布时间】:2017-03-16 23:28:24
【问题描述】:
我正在使用 Python 将 json 文件转换为更易于阅读的输出,并且该 json 中的特定条目可以采用以下格式之一。我正在尝试创建一种方法来处理创建适当的输出而不检查类型。
"responseType": null
或
"responseType": "FEATURE MODEL"
或
"responseType": {
"type": "array",
"of": "Feature"
}
或
"responseType": {
"type": "array",
"of": {
"type": "number",
"format": "int32"
}
}
在每种情况下我想要的输出是这样的:
The responseType is null
The responseType is a Feature Model
The responseType is an array of Feature
The responseType is an array of int32 numbers
我是 Python 新手,我的第一个倾向是进行大量类型检查和字符串连接。即:
str = "The response type is "
if type(obj["responseType"]) is str:
str += obj["responseType"]
elif type(obj["responseType"]) is dict:
str += obj["responseType"]["type"] + " "
if type(obj["responseType"]["of"] is str
str += obj["responseType"]["of"]
else:
#dict output
#etc...
elif type(obj["responseType"] is None:
print("The response type is null")
考虑到我反复读到你永远不应该检查类型,这样做感觉非常幼稚和不正确。
那么,在不进行所有类型检查的情况下,处理这种情况的 Python 方法是什么?
【问题讨论】:
-
我不认为你可以做很多事情来改善这一点。这是一个设计不佳的数据结构。
-
@Barmar:这并不意味着代码本身的结构不能更好。
-
@martineau 和 @martijn-pieters 的答案都提供了可运行的解决方案。但我不确定我能否真正判断哪个是“更好”的答案。作为 python 的新手,我会说@martineau 的解决方案更具可读性,但我还不知道@martijn-pieters 做了什么。对我有帮助,两者都利用了嵌套
TypeErrors的技术 -
两个答案的本质是相同的:“使用异常而不是类型检查”这将使代码更加“Pythonic”。当然,我有偏见,但除此之外,你所说的可读性和能够理解代码似乎会打破僵局——因为这些也是这个概念的重要方面。
标签: python json duck-typing