1

I'm try to create a simple JSON object from the output of a database query that would look something like this:

json_obj= {
           '1': 'test_1',
           '2': 'test_2',
           '3': 'test_3',
           '4': 'test_4',
           '5': 'test_5',
           }

So far I've been trying for loops and json.dumps but cannot get it right:

cat_list = []
cats = Category.query.all()
for cat in cats:
    item = {
            cat.id: cat.name
           }
    cat_list.append(item)

json_cat_list = json.dumps(cat_list)

This does create a JSON object but not exactly what I'm looking for.

json_obj= {
           {'1': 'test_1'},
           {'2': 'test_2'},
           {'3': 'test_3'},
           {'4': 'test_4'},
           {'5': 'test_5'},
           }

Any suggestions on how to do this?

Many thanks

1 Answer 1

5

You want a single dict object, not a list of them.

cat_dict = {}                         # 1
for cat in Category.query.all():
    cat_dict[cat.id] = cat.name       # 2

json_cat_dict = json.dumps(cat_dict)  # 3

Or, (as @Daniel Roseman mentioned below) for conciseness, you can condense everything into a single dictionary comprehension:

cat_dict = {cat.id: cat.name for cat in Category.query.all()}
Sign up to request clarification or add additional context in comments.

1 Comment

Or as a single-line dict comprehension: cat_dict = {cat.id: cat.name for cat in Category.query.all()}.

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.