I am unsing json.dump
to generate multiple JSON files. The JSON is like this:
[
{"any": 2023},
{
"dia": 24,
"mes": 1,
"any": 2023,
"mes_referencia": 12,
"any_referencia": 2022,
"calendari_nom": "CTH"
}]
But what I need is that the first part, {"any":2023}
, does not generate a JSON file.
I am using this code where json_output
is the JSON script:
data = json.loads(json_output)
for i, d in enumerate(data, 1):
with open(f"data_out_{i}.json", "w") as f_out:
json.dump(d, f_out, indent=4)
Is there a way omit the creation of the first file before the creation of the file?
2
Answers
I have resolved with an If clause, like this:
In this way, the first part is not generated.
Thanks
If it’s always the first item, you can check for that in the loop, i.e.
or just skip the first item altogether by slicing
data
:Alternately, if you want to skip any item that only has a single
any
key:Finally, if you want to be able to skip items and not have gaps in the numbering series, you can use a separate
itertools.count
for numbering them: