Jowey
Jowey

Reputation: 61

how to ignore all empty key and values from JSON where the key is empty in python

I have a JSON file that contains this data :

[{
    "text": "1",
    "entities": []
},
{
    "text": "2",
    "entities": []
},

{
    "text": "GIARETTON ANTONIO C.F. GRTNTN69A22H829L CODICE P.0.D. IT001E30069505",
    "entities": [
        {
            "text": "GIARETTON ANTONIO C.F. GRTNTN69A22H829L CODICE P.0.D. IT001E30069505",
            "type": "Purpose of the transfer",
            "start_idx": 0,
            "end_idx": 68
        }
    ]
}]

I want to ignore all the keys and values that do not have data within the entities so that the final out put will look like this :

[ {
    "text": "GIARETTON ANTONIO C.F. GRTNTN69A22H829L CODICE P.0.D. IT001E30069505",
    "entities": [
        {
            "text": "GIARETTON ANTONIO C.F. GRTNTN69A22H829L CODICE P.0.D. IT001E30069505",
            "type": "Purpose of the transfer",
            "start_idx": 0,
            "end_idx": 68
        }
    ]
}]

Upvotes: 0

Views: 576

Answers (2)

Agent Biscutt
Agent Biscutt

Reputation: 737

Here is a function to do it, provided that the data structure is always the same:

def unpck(a,key="entities"):
  b=[]
  for x in a:
    if len(x[key])>0:
      b.append(x)
  return(b)

This function returns a list of the dictionaries that have data in the "entities", or any other key you want.

Upvotes: 1

funnydman
funnydman

Reputation: 11396

Learn how to write list comprehensions:

print([obj for obj in data if obj['entities']])

Upvotes: 1

Related Questions