+ 1

Create json and append dict to list?

I am newbie and want to achieve the following: http://www.objgen.com/json/models/ykcJ { "background": { "elements": [ { "id": "1", "filename": "Blue.jpg" }, { "id": "2", "filename": "Red.jpg" }, { "id": "3", "filename": "Green.jpg" }, { "id": "4", "filename": "Brown.jpg" } ] } My code: def getElement(dir): counter = 0 for path in pathlib.Path(dir).iterdir(): if path.is_file(): value = { "id": counter += 1, "name": cleanName(path.name), "filename": path.name } elements = [] elements.append(value) print('element: ',elements) return elements

25th Aug 2021, 7:10 PM
Adarsh Mamgain
Adarsh Mamgain - avatar
2 odpowiedzi
+ 1
Try to move this line elements = [] Below this line counter = 0 It seems you are recreating <elements> inside the loop.
26th Aug 2021, 1:17 AM
Ipang
+ 1
Ipang 🤦 stupidest mistake 😅 Thank You
26th Aug 2021, 7:31 AM
Adarsh Mamgain
Adarsh Mamgain - avatar