Python 如何计算 JSON 数据中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27315472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count items in JSON data
提问by mierzej
How I can get the number of elements in node of JSON data?
如何获取 JSON 数据节点中的元素数量?
JSON:
JSON:
{
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find":true
}
]
}
I need to get the number of elements from node data['result'][0]['run']
. It should be 3, but I can't find how to do it in Python.
我需要从 node 获取元素数data['result'][0]['run']
。它应该是 3,但我找不到如何在 Python 中做到这一点。
采纳答案by pnv
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
将其转换为 dict。
回答by Muad'Dib
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
你很接近。一个非常简单的解决方案是从返回的“运行”对象中获取长度。无需担心“加载”或“加载”:
len(data['result'][0]['run'])