Shadows1996
Shadows1996

Reputation: 114

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

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=(',', ': '))
)

Upvotes: 1

Views: 2164

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

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=(',', ': '))
)

Upvotes: 4

Related Questions