awdoibbbbbbb2
awdoibbbbbbb2

Reputation: 63

How to create a series of JSON objects given a list in python?

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.

Upvotes: 1

Views: 130

Answers (1)

quamrana
quamrana

Reputation: 39354

Just create the objects before converting to json.

obj = { name:{} for name in subfolders }
...
json.dump(obj, f, indent=2)

Upvotes: 2

Related Questions