Reputation: 335
With the following python code :
import fnmatch
import os
import json
data = []
for file in os.listdir('./images'):
if fnmatch.fnmatch(file, '*.jpg'):
data.append(file)
with open('asd.json', 'w') as f:
json.dump({'data' : {"name": data}},f,sort_keys = True, indent = 4,
ensure_ascii = False)
I am getting the following json output in file asd.json
:
{
"data": {
"name": [
"got01.jpg",
"got02.jpg"
]
}
}
But I want my json output in asd.json
as :
{
"data": [
{
"name": "got01.jpg"
},
{
"name": "got02.jpg"
}
]
}
Can you suggest a better approach to get the output in desired structure?
Upvotes: 0
Views: 84
Reputation: 541
Try
json.dump({'data' : [{"name": x} for x in data]},f,sort_keys = True, indent = 4, ensure_ascii = False)
Full code:
import fnmatch
import os
import json
data = []
for file in os.listdir('./images'):
if fnmatch.fnmatch(file, '*.jpg'):
data.append(file)
with open('asd.json', 'w') as f:
json.dump({'data' : [{"name": x} for x in data]},f,sort_keys = True, indent = 4,
ensure_ascii = False)
Upvotes: 2