[英]How to count items in JSON data
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']
.我需要从节点
data['result'][0]['run']
中获取元素的数量。 It should be 3, but I can't find how to do it in Python.它应该是 3,但我在 Python 中找不到如何做到这一点。
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。
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'])
I was doing the same task, except that I had to read the data from a JSON file instead of a variable like yours, here is how I did it:我在做同样的任务,除了我必须从 JSON 文件而不是像你这样的变量中读取数据,我是这样做的:
import json
with open('movie.json', encoding='utf8') as JSONFile:
data = json.load(JSONFile)
print(len(data['movie'][0]))
and my sample JSON element in the file looks like this:我在文件中的示例 JSON 元素如下所示:
{
"movie": [
{
"Id": 1,
"Title": "Inception",
"Overview": "Cobb, a skilled thief who commits corporate espionage by infiltrating the subconscious of his targets is offered a chance to regain his old life as payment for a task considered to be impossible: \"inception\", the implantation of another person's idea into a target's subconscious.",
"Tagline": "Your mind is the scene of the crime.",
"Budget": 160000000.0000,
"Revenue": 825532764.0000,
"ImdbUrl": "https:\/\/www.imdb.com\/title\/tt1375666",
"TmdbUrl": "https:\/\/www.themoviedb.org\/movie\/27205",
"PosterUrl": "https:\/\/image.tmdb.org\/t\/p\/w342\/\/9gk7adHYeDvHkCSEqAvQNLV5Uge.jpg",
"BackdropUrl": "https:\/\/image.tmdb.org\/t\/p\/original\/\/s3TBrRGB1iav7gFOCNx3H31MoES.jpg",
"OriginalLanguage": "en",
"ReleaseDate": "2010-07-15T00:00:00",
"RunTime": 148,
"Price": 9.90,
"CreatedDate": "2021-04-03T16:51:30.1633333",
"UpdatedDate": null,
"UpdatedBy": null,
"CreatedBy": null,
"genres": [
{
"id": 1,
"name": "Adventure"
},
{
"id": 6,
"name": "Action"
},
{
"id": 13,
"name": "Science Fiction"
}
]
}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.