skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have resolved with an If clause, like this:

    import json
    
        data = json.loads(json_output)
        
        for i, d in enumerate(data, 0):
            if i==0:
                None
            else:
                with open(f"data_out_{i}.json", "w") as f_out:
                    json.dump(d, f_out, indent=4)
    

    In this way, the first part is not generated.

    Thanks


  2. If it’s always the first item, you can check for that in the loop, i.e.

    for i, d in enumerate(data, 1):
        if i == 1:
            continue
        ...
    

    or just skip the first item altogether by slicing data:

    for i, d in enumerate(data[1:], 1):
        ...
    

    Alternately, if you want to skip any item that only has a single any key:

    for i, d in enumerate(data, 1):
        if set(d) == {'any'}:
            continue
        ...
    

    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:

    counter = itertools.count(1)
    for d in data:
        if "foo" in d:  # skip this
            continue
        if not d:  # skip an empty entry
            continue
        # (etc...)
        i = next(counter)
        with open(f"data_out_{i}.json", "w") as f_out:
            json.dump(d, f_out, indent=4)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search