如何计算 JSON 数据中的项目

如何得到 JSON 数据节点中的元素数?

杰森:

{
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find":true
}
]
}

我需要从节点 data['result'][0]['run']获取元素的数量。它应该是3,但我找不到如何在 Python 中做到这一点。

225651 次浏览
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'])

把它转换成字典。

很接近了。一个非常简单的解决方案就是从返回的“ run”对象中获取长度。不必为“装载”或“装载”而烦恼:

len(data['result'][0]['run'])

我也在做同样的工作,只不过我不得不从一个 JSON 文件中读取数据,而不是像你的那样读取变量,我是这样做的:

import json
with open('movie.json', encoding='utf8') as JSONFile:
data = json.load(JSONFile)
print(len(data['movie'][0]))

文件中的示例 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"
}
]
}]