解析json文件并使用python计算每个对象下的项数
我有这个json文件:解析json文件并使用python计算每个对象下的项数,python,json,Python,Json,我有这个json文件: "compileFlags": { "useVarcharZplitterRemoveIf": false, "useVarcharZplitterSortVal": false, "useVarcharZplitterSortKey": false, "useVarcharZplitterJoinVal": false, "useVarcharZplitterJoinKey": true, }, "runtimeFlags": {
"compileFlags": {
"useVarcharZplitterRemoveIf": false,
"useVarcharZplitterSortVal": false,
"useVarcharZplitterSortKey": false,
"useVarcharZplitterJoinVal": false,
"useVarcharZplitterJoinKey": true,
},
"runtimeFlags": {
"useShortcutJoin": true,
"useMemorySpool": true,
},
"runtimeGlobalFlags": {
"useMetadataServer": true,
"metadataServerIp1": 127,
},
"server":{
"gpu": 0,
"port": 5000,
}
}
我希望能够计算此json文件中的每个对象,例如:
compileFlags=5(因为它名下有18项)
运行时间间隔=2
这是我的代码:
with open(json_file_path, "r") as f:
data = json.load(f)
print(len(data["compileFlags"]))
print(len[data["runtimeFlags"]])
print(len[data["runtimeGlobalFlags"]])
print(len[data["server"]])
read_json_file(path_to_json_file_location)
运行时,我收到以下错误消息:
TypeError: 'builtin_function_or_method' object is not subscriptable
我做错了什么 您可以使用下面的函数返回包含每个元素计数的字典
count = {}
for k, v in data.items():
count[k] = len(v)
print(count)
OUT: {'compileFlags': 5, 'runtimeFlags': 2, 'runtimeGlobalFlags': 2, 'server': 2}
你的代码有输入错误,
len[data[“runtimelags”]
应该是len(data[“runtimelags”])
和下面的所有行。哦,是的,我错过了,谢谢!IBelow是您问题的答案。@tupacshakur请看我的答案,这个答案可以用来计算任何json结构中的元素。