1

I have this code that allows me to create a JSON file from a list, creates the list, checks that the elements don't repeat, and then creates the JSON file.

import json

res = []
seen = set()

def add_entry(res, id, tf1, tf2, tf3):

    # check if in seen set
    if (id, tf1, tf2, tf3) in seen:
        return res

    # add to seen set
    seen.add(tuple([id, tf1, tf2, tf3]))

    # append to results list
    res.append({'metrica': id, 'ft1': tf1, 'tf2': tf2, 'tf3': tf3})

    return res

args = ['ext:tech.DB2', '40,023', '168,481', '15,55']
res = add_entry(res, *args)

args = ['ext:bim.DB2', '25,02', '18,81', '5,35']
res = add_entry(res, *args)

def write_to_json(lst, fn):
    with open(fn, 'a', encoding='utf-8') as file:
        for item in lst:
            x = json.dumps(item, indent=4)
            file.write(x + '\n')

#export to JSON
write_to_json(res, 'elements.json')

Only the JSON file is not a real JSON file:

{
    "metrica": "ext:bim.DB2",
    "ft1": "40,023",
    "tf2": "168,481",
    "tf3": "15,55"
}
{
    "metrica": "ext:bim.DB2",
    "ft1": "25,02",
    "tf2": "18,81",
    "tf3": "5,35"
}

How can I make it like this:

{"data":[{
    "metrica": "ext:bim.DB2",
    "ft1": "40,023",
    "tf2": "168,481",
    "tf3": "15,55"
},
{
    "metrica": "ext:bim.DB2",
    "ft1": "25,02",
    "tf2": "18,81",
    "tf3": "5,35"
}]}

the json file I generate it in the code and then dynamically I need to pass it to another function, even if I wanted to, I could not change the values manually, also because I would have more than 900 elements to change, how can I do it dynamically?

1
  • Does this answer your question? How to dynamically build a JSON object? You already have the list, for your expected output json.dump({"data": lst}, file, indent=4) should ideally be enough. Commented Dec 5, 2023 at 14:43

1 Answer 1

4

Instead of saving each element of list separately, save the entire list.

def write_to_json(lst, fn):
    out = {}
    out["data"] = lst
    with open(fn, 'w', encoding='utf-8') as file:
        x = json.dumps(out, indent=4)
        file.write(x + '\n')

To simplify further,

x = json.dumps(out, indent=4)
file.write(x + '\n')

is more or less the same as json.dump(out, file, indent=4) (dump writes directly to file, dumps returns a string - same is true for analogous load and loads methods that read from file or parse a string). We can then get rid of explicit out object and just create it inside the dump function. That gives us much cleaner version that Abdul suggested in comment.

def write_to_json(lst, fn):
    with open(fn, 'w', encoding='utf-8') as file:
        json.dump({'data': lst}, file, indent=4)
Sign up to request clarification or add additional context in comments.

3 Comments

(Also, don't use 'a'. Use 'w' to ensure a valid file each time)
@quamrana Fair, just copied what was in OPs original code
Yes, I realised that. Anyway +1 for a working answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.