[英]Remove entire JSON object if it contains a specified phrase (from a list in python)
Have a JSON file output similar to:有一个类似于以下内容的 JSON 文件输出:
{
"object1": {
"json_data": "{json data information}",
"tables_data": "TABLES_DATA"
},
"object2": {
"json_data": {json data information}",
"tables_data": ""
}
}
Essentially, if there is an empty string for tables_data
as shown in object2
(eg. "tables_data": ""
), I want the entire object to be removed so that the output would look like:本质上,如果tables_data
有一个空字符串,如object2
所示(例如"tables_data": ""
),我希望删除整个对象,以便输出如下所示:
{
"object1": {
"json_data": "{json data information}",
"tables_data": "TABLES_DATA"
}
}
What is the best way to go about doing this?这样做的最佳方法是什么? Each of these objects correspond to a separate index in a list that I've appended called summary[]
.这些对象中的每一个都对应于我附加的名为summary[]
的列表中的一个单独索引。
To achieve this, you could iterate through the JSON dictionary and test the tables_data
values, adding the objectX
elements to a new dictionary if their tables_data
value passes the test:为此,您可以遍历 JSON 字典并测试tables_data
值,如果它们的tables_data
值通过测试,则将objectX
元素添加到新字典中:
new_dict = {k: v for k, v in json_dict.items()
if v.get("tables_data", "") != ""}
If your JSON objectX
is stored in a list as you say, these could be processed as follows using a list comprehension:如果您的 JSON objectX
存储在您所说的列表中,则可以使用列表理解按如下方式处理这些:
filtered_summary = [object_dict for object_dict in summary
if object_dict.get("tables_data", "") != ""]
Unless you have compelling reasons to do otherwise, the pythonic way to filter out a list or dict (or any iterable) is not to change it in place but to create a new filtered one.除非您有令人信服的理由不这样做,否则过滤列表或字典(或任何可迭代对象)的 Pythonic 方法不是就地更改它,而是创建一个新的过滤器。 For your case this would look like对于您的情况,这看起来像
raw_data = YOUR_DICT_HERE_WHEREVER_IT_COMES_FROM
# NB : empty string have a false value in a boolean test
cleaned_data = {k:v for k, v in raw_data.items() if not v["table_data"]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.