I am implementing an API that returns how many users are using a particular app.
For example, say I want to return data that says
10 people are using only App1, 8 are using only App2, 8 are using only App3, and 15 are using both App1 and App2, and 20 are using all App1, App2, and App3.
How do we design the response structure in JSON?
I thought returning it in comma separated format
{
"App1": 10,
"App2": 8,
"App3": 8,
"App1,App2": 15,
"App1,App2,App3": 20
}
Is this format is right and semantically correct?
I thought of Array as well,
[
{"key": ["App1"], "count": 10},
{"key": ["App2"], "count": 8},
{"key": ["App3"], "count": 8},
{"key": ["App1", "App2"], "count": 15},
{"key": ["App1", "App2", "App3"], "count": 20}
]
but was doubtful on this on whether it is semantically correct.
Is there any better way? What is the best way to represent this data?
CodePudding user response:
I think the solution you have tried is very limited. Your solution is fine for 3 apps but let's say that you later want to add few more apps then you have add those return types as well.
Instead of the above I would like to suggest as below. This suggestion has low coupling and can work for any number of apps
{
"IndividualAppUsersCount":[10,8,8],
"MultipleAppUsersCount":[
{
"AppsInUse":"App1 App2",
"Count":15
},
{
"AppsInUse":"App1 App2 App3",
"Count":20
}
]
}
The benefit of using this approach is that you are not limited to predefined apps but can easily work for 0 to n number of apps. Just loop through the array and get the corresponding result.
You can even improve the above result by following as below.
{
"AppUsersCount":[
{
"AppsInUse":"App1",
"Count":10
},
{
"AppsInUse":"App2",
"Count":8
},
{
"AppsInUse":"App3",
"Count":8
},
{
"AppsInUse":"App1, App2",
"Count":15
},
{
"AppsInUse":"App1, App2, App3",
"Count":20
}
]
}
I hope this answers your question. However if you still have any other question, let me know I will be glad to answer.
Thank you for reading.
CodePudding user response:
I would go with the following structure:
{
"usersCount": [
{
"apps": ["App1"],
"userCount": 10
},
{
"apps": ["App2"],
"userCount": 8
},
{
"apps": ["App3"],
"userCount": 8
},
{
"apps": ["App1", "App2"],
"userCount": 15
},
{
"apps": ["App1", "App2", "App3"],
"userCount": 20
}
]
}
This would make it easier to parse and handle multiple Apps (when compared with String split for example). To make it a little bit more strongly typed I would make App1
, App2
and App3
values of an App
enumeration.