代码之家  ›  专栏  ›  技术社区  ›  justaguy

如何删除带有空引号的json元素?

  •  -2
  • justaguy  · 技术社区  · 2 年前

    python3 下面的代码我阅读了所有 objects 在中 json 然后循环通过 elements 在中 json 。如果我只搜索 id is not None 则移除该元素和空值。然而,当我添加 or 语句来删除 id is not "" 整个文件都不使用 id 在删除的或语句中。刚接触 python 我不确定我做错了什么。谢谢:)。

    文件

    {
    "objects": [
        {
            "version": "1",
            "list": [
                {
                    "
                        "json": null
                    },
                    "id": "",
                }
            ],
            "h": "na"
        },
    {
            "version": "1",
            "list": [
                {
                    "
                        "json": null
                    },
                    "id": "This has text in it and should be printed",
                }
            ],
            "h": "na"
        },
    {
            "version": "1",
            "list": [
                {
                    "
                        "json": null
                    },
                    "id": null,
                }
            ],
            "h": "na"
        }
    ]
    }
    

    渴望的

    {
            "version": "1",
            "list": [
                {
                    "
                        "json": null
                    },
                    "id": "This has text in it and should be printed",
                }
            ],
            "h": "na"
        },
    

    蟒蛇3

    if v["id"] is not None or v['id'] is not "":
    

    还尝试了以下内容和 身份证件 已更改:

    for obj in data['objects']:
    if obj.get('id') is "":
        obj['description'] = 'na'
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   John Gordon    2 年前
    if v["id"] is not None or v['id'] is not "":
    

    无论值是多少,此语句都将 总是 是真的。

    如果该值为None,则 is not "" 部分将是真实的。

    如果该值为空字符串,则 is not None 部分将是真实的。

    如果这个值是其他值,那么这两个部分都是真的。

    正如@Pranav所评论的,你想使用 and 在这里,不是 or .