Python 从JSON中删除JSON对象?
我有一个json数组Python 从JSON中删除JSON对象?,python,json,Python,Json,我有一个json数组 { "query": { "bool": { "must": [], "should": [ { "match": { "Name": { "query": "Nametest", "fuzziness": 3, "boost": 5 } }
{
"query": {
"bool": {
"must": [],
"should": [
{
"match": {
"Name": {
"query": "Nametest",
"fuzziness": 3,
"boost": 5
}
}
},
{
"match": {
"Address": {
"query": "NONE",
"fuzziness": 3,
"boost": 4
}
}
},
{
"match": {
"Site": {
"query": "Adeswfvfv",
"fuzziness": 3,
"boost": 4
}
}
},
{
"match": {
"Phone": {
"query": "5680728.00",
"fuzziness": 2,
"boost": 4
}
}
}
],
"minimum_should_match": 2
}
}
}
所以我想做的是如果在json['query']['bool']['should']中,如果“query”是“NONE”,那么我想删除这个json数组,新的json将被删除
{
"query": {
"bool": {
"must": [],
"should": [
{
"match": {
"Name": {
"query": "Nametest",
"fuzziness": 3,
"boost": 5
}
}
},
{
"match": {
"Site": {
"query": "Adeswfvfv",
"fuzziness": 3,
"boost": 4
}
}
},
{
"match": {
"Phone": {
"query": "5680728.00",
"fuzziness": 2,
"boost": 4
}
}
}
],
"minimum_should_match": 2
}
}
}
我尝试过在json上迭代,并使用了del(jsonarray)和pop(jsonarray),但没有任何帮助
尝试使用python json库,但失败
for e in q['query']['bool']['should']:
... if "NONE" in str(e['match']):
... del(e)
这应该会有所帮助
import pprint
d = {'query': {'bool': {'minimum_should_match': 2, 'should': [{'match': {'Name': {'query': 'Nametest', 'boost': 5, 'fuzziness': 3}}}, {'match': {'Address': {'query': 'NONE', 'boost': 4, 'fuzziness': 3}}}, {'match': {'Site': {'query': 'Adeswfvfv', 'boost': 4, 'fuzziness': 3}}}, {'match': {'Phone': {'query': '5680728.00', 'boost': 4, 'fuzziness': 2}}}], 'must': []}}}
d["query"]['bool']['should'] = [i for i in d["query"]['bool']['should'] if list(i['match'].items())[0][1]["query"] != 'NONE']
pprint.pprint(d)
输出:
{'query': {'bool': {'minimum_should_match': 2,
'must': [],
'should': [{'match': {'Name': {'boost': 5,
'fuzziness': 3,
'query': 'Nametest'}}},
{'match': {'Site': {'boost': 4,
'fuzziness': 3,
'query': 'Adeswfvfv'}}},
{'match': {'Phone': {'boost': 4,
'fuzziness': 2,
'query': '5680728.00'}}}]}}}
我写了这篇文章,但这似乎很复杂
for p,c in enumerate(json['query']['bool']['should']):
if list(c["match"].values())[0]["query"] == "NONE":
json['query']['bool']['should'].pop(p)
print(json)
让我们看看你尝试了什么!我在Python3.4上发现了这样一个类型错误:'dict_items'对象不支持索引try
d[“query”['bool']['should']=[I for I in d[“query”]['bool']['should']if list(I['match'].items())[0][1][“query”!='NONE']
工作得很好,这是在stackoverflow上删除python jsonobject的第一个解决方案,谢谢buddy