在python中从JSON中选择必需的字段

问题描述 投票:-1回答:1

下面是我拥有的JSON数据,我只想获得名称,after_count。

{
    "total_count": 125,
    "limit": 100,
    "operatingsystems": [
        {
            "category": null,
            "name": "abc",
            "total_count": 1,
            "notes": "",
            "after_count": 11,
            "id": 1,
            "aliases": []
        },
        {
            "category": null,
            "name": "cdef",
            "total_count": 2,
            "notes": "",
            "after_count": 62,
            "id": 2,
            "aliases": []
        },

我的代码:

data = [item for item in objects if item["after_count"] >= 0]

输出我得到:

"
a
l
i
a
s
e
s
"
:

[
]

有人可以指导我正确的方向。

python python-3.x python-2.7 python-requests
1个回答
1
投票

我在你的问题中为字符串添加了几个字符,以便json的语法完整,然后将其填充到json.loads中以创建一个json对象。

s = '''{
    "total_count": 125,
    "limit": 100,
    "operatingsystems": [
        {
            "category": null,
            "name": "abc",
            "total_count": 1,
            "notes": "",
            "after_count": 11,
            "id": 1,
            "aliases": []
        },
        {
            "category": null,
            "name": "cdef",
            "total_count": 2,
            "notes": "",
            "after_count": 62,
            "id": 2,
            "aliases": []
        }]}'''

import json

j = json.loads(s)

print (j["operatingsystems"][0]["name"])
print (j["operatingsystems"][0]["after_count"])
print (j["operatingsystems"][1]["name"])
print (j["operatingsystems"][1]["after_count"])

最后四个语句显示了如何访问所需的项目。

© www.soinside.com 2019 - 2024. All rights reserved.