1

Essentially need to create a new JSON object for each item in my list using python. I'm able to output the contents of my list, but want to create a new JSON object for each list item that I output. How would I go about doing this?

My code:

subfolders = [ f.path for f in os.scandir(rootdir) if f.is_dir() ]
subfolders = [sub.replace(rootdir + '\\', '') for sub in subfolders]

with open('summary.json', 'w') as f:
    json.dump(subfolders, f, indent=2)

Current Sample Output:

[
  "subfolder1",
  "subfolder2",
  "subfolder3"
]

Desired Sample Output:

{
  "subfolder1": {},
  "subfolder2": {},
  "subfolder3": {}
}

PS: within each of those JSON objects, I'll need to populate the information held within those subfolders, which are also stored in lists. Any assistance on that would also be appreciated, thanks in advance.

1 Answer 1

2

Just create the objects before converting to json.

obj = { name:{} for name in subfolders }
...
json.dump(obj, f, indent=2)
Sign up to request clarification or add additional context in comments.

2 Comments

This is what I needed, thank you. I'm still curious as to how I can populate information into those objects as well. Essentially, each of those subfolders have 2 files which need their content to be written into the created objects.
That needs to be a new question. See if you can ask one which is focused solely on that part of the problem.

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.