0

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

check the curly brackets in json.dump({'data' : [{"name": x} for x in data],f,sort_keys = True, indent = 4, ensure_ascii = False)
Yes, I have fixed it now.

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.