Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove JSON block based on a condition

I am trying to remove a block based on key – value in json file in python. A snippet of the JSON file is as follow:

[
  {
    "endTime" : "2021-01-21 07:44",
    "artistName" : "Edward Sharpe & The Magnetic Zeros",
    "trackName" : "Home",
    "msPlayed" : 241536
  },
  {
    "endTime" : "2021-01-21 08:48",
    "artistName" : "t.A.T.u.",
    "trackName" : "All The Things She Said",
    "msPlayed" : 186644
  },
  ...
]

What I can’t do is remove the "entry" between 2 { } if msPlayed is < 30000 mS. Any suggestions?

Edit: what I tried so far is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import json

obj  = json.load(open("StreamingHistory0.json", encoding= 'utf-8' ))

# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in range(len(obj)):
    if obj[i]["msPlayed"] < 29999:
        obj.pop(i)
        break

# Output the updated file with pretty JSON
open("updated-file.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

>Solution :

A single line with list comprehension should do the trick for you. See https://rextester.com/YNAO67705

expected = [element for element in data if element['msPlayed'] < 30000 ]

Full Code:

import json
data  = json.load(open("StreamingHistory0.json", encoding= 'utf-8' ))

# Iterate through the objects in the JSON and filter                     
expected = [element for element in data if element['msPlayed'] < 30000 ]

# Output the updated file with pretty JSON                                      
open("updated-file.json", "w").write(
    json.dumps(expected, sort_keys=True, indent=4, separators=(',', ': '))
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading