【问题标题】:Selecting the required fields from JSON in python在python中从JSON中选择必填字段
【发布时间】:2018-01-29 23:37:59
【问题描述】:

以下是我拥有的 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】:

    我在您问题中的字符串中添加了几个字符,以便 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"])
    

    最后四个语句显示了如何访问您想要的项目。

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 2020-04-16
      • 2015-12-10
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多