0

As a part of my RESTful API I found myself needing to return a json with "variable" keys, I'll try to make things more clear with a simple example:

I have different groups, each group has a group_id, so the expected return would be:

{
    1: {
         "name": "first_group_name",
         ...
       },
    5: {
         "name": "second_group_name",
         ...
       }
}

As you can see, the keys (group_ids) in the root json are not something I can hard-code in my model, all I know is they are integers. Can anyone help with a solution to this problem?

Gal Pressman
  • 130
  • 1
  • 13
  • Your question is not clear enough to answer without wild guesses. Are these 'keys' associated to the objects? Are they a result of a query sent by the client? Your example looks quite atypical. If you are returning a group of objects that are a result of a query, why don't you return them in an array? why isn't the 'key' (which I presume is actually an ID) part of the object? – AArias Jan 01 '17 at 00:34
  • Your wild guesses are right, the keys are part of the objects. I can return an array with the id inside, but returning a "dictionary" makes more sense for easier access. – Gal Pressman Jan 01 '17 at 08:57
  • 1
    It really does not. Read the community wiki answer to this question: http://stackoverflow.com/questions/671118/what-exactly-is-restful-programming and check out the example responses with collections of objects. Although there's no official standard, there's wide consensus on good practices for REST APIs and also initiatives that attempt standardization like the Open API Initiative (https://github.com/OAI). That doesn't mean it's wrong that you want to generate your example (calling it REST would be debatable) but in that case, given the information provided, @metmirr's answer looks fitting. – AArias Jan 01 '17 at 14:11
  • Thank you for the help! I understand what I'm trying to do is not good practice, which is probably the reason I could not find an appropriate flask model for this. I'll return a list like you suggested. – Gal Pressman Jan 01 '17 at 14:57

1 Answers1

0

I am not sure this is what you need but you can do something like this:

return_values = {}
group_ids = [1, 2, 3, 4]
for g_id in group_ids:
    return_values[g_id] = { "name": "%s_group_name"%i }

print(return_values)

#{1: {'name': 'group_1'}, 2: {'name': 'group_2'}, 3: {'name': 'group_3'}, 4: {'name': 'group_4'}}

if you are using you can modify the code as you want.

metmirr
  • 4,234
  • 2
  • 21
  • 34