Home > Software design >  how to ignore all empty key and values from JSON where the key is empty in python
how to ignore all empty key and values from JSON where the key is empty in python

Time:11-05

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
        }
    ]
}]

CodePudding user response:

Learn how to write list comprehensions:

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

CodePudding user response:

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.

  • Related