Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解析json文件并使用python计算每个对象下的项数_Python_Json - Fatal编程技术网

解析json文件并使用python计算每个对象下的项数

解析json文件并使用python计算每个对象下的项数,python,json,Python,Json,我有这个json文件: "compileFlags": { "useVarcharZplitterRemoveIf": false, "useVarcharZplitterSortVal": false, "useVarcharZplitterSortKey": false, "useVarcharZplitterJoinVal": false, "useVarcharZplitterJoinKey": true, }, "runtimeFlags": {

我有这个json文件:

"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结构中的元素。