3 回答
TA贡献1873条经验 获得超9个赞
import json
data={}
with open('C:\\Users\\Takvaviya_PC_007\\Downloads\\via_region_data.json','r') as file:
original = json.load(file)
for p in original:
# print(p)
# print(original[p])
if original[p]['regions']!=[]:
data[p]=original[p]
print(data)
with open('C:\\Users\\Takvaviya_PC_007\\Downloads\\pulse2.json', 'w') as outfile:
json.dump(data, outfile)
TA贡献1821条经验 获得超4个赞
你快到了,如果你尝试在每个文件中加载一个带有 json 对象的文件,你会得到一个解码错误,因为它不是有效的 json。
相反,您遍历每一行,然后加载 json 并在值为 时regions转储truthy。
在 python 中,空lists是空的,falsy因此将过滤掉具有空数组的区域。
import json
with open('filtered_data.json', 'w') as outfile:
with open('all_data.json') as json_file:
for line in json_file:
data = json.loads(line)
if data['regions']:
outfile.write(json.dumps(data)+'\n')
all_data.json
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group13918.jpg", ...other data...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14218.jpg", ...other data...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14219.jpg", ...other data...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14222.jpg", ...other data...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14243.jpg", ...other data...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14277.jpg", ...other data...}
过滤数据.json
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group13918.jpg", ...other data ...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14218.jpg", ...other data ...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14219.jpg", ...other data ...}
{"filename": "SPI_121218_SITE2_NDVI_25m_transparent_mosaic_group14222.jpg", ...other data ...}
TA贡献1813条经验 获得超2个赞
首先将 json 文件加载为字典,
import json
with open('<input>.json','r') as file:
dct = json.load(file)
然后我们遍历字典并附加所有具有regions非空列表键的字典。
li = []
for k,v in dct.items():
#Check if regions key exists, and the list is non-empty
if 'regions' in v and v['regions']:
li.append(v)
print(li)
然后我们将结果列表保存到另一个 json。
with open('<output>.json', 'w') as outfile:
json.dump(li, outfile)
添加回答
举报