根据条件删除 JSON 块
Remove JSON block based on a condition
我正在尝试根据 python 中 json 文件中的键值删除一个块。 JSON 文件的片段如下:
[
{
"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
},
...
]
如果 msPlayed
是 < 30000
毫秒,我不能做的是删除 2 { }
之间的 "entry"
。有什么建议吗?
编辑:到目前为止我尝试的是
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=(',', ': '))
)
单行 列表理解 应该可以解决问题。 参见 https://rextester.com/YNAO67705
expected = [element for element in data if element['msPlayed'] < 30000 ]
完整代码:
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=(',', ': '))
)
我正在尝试根据 python 中 json 文件中的键值删除一个块。 JSON 文件的片段如下:
[
{
"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
},
...
]
如果 msPlayed
是 < 30000
毫秒,我不能做的是删除 2 { }
之间的 "entry"
。有什么建议吗?
编辑:到目前为止我尝试的是
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=(',', ': '))
)
单行 列表理解 应该可以解决问题。 参见 https://rextester.com/YNAO67705
expected = [element for element in data if element['msPlayed'] < 30000 ]
完整代码:
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=(',', ': '))
)