Follwoing this post, I have a SQL query that returns the following table:
team (json)
"{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]}"
"{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}"
I need to aggregate this into JSON to use in my app. I'm using the following:
SELECT json_agg(u) FROM (SELECT DISTINCT ON (t.team->>'Name') t.team
FROM matches m, json_array_elements(m.match->'Teams') t(team)
ORDER BY t.team->>'Name', m.id DESC) AS u
Which returns:
"[{"team":{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]}},
{"team":{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}}]"
So it appears that it has put a "team" tag before each object. This doesn't serialise in my C# app properly. After reading this question I believe that this might not be correct JSON. Is this correct?
I want to get it in the following form:
"[{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]},
{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}]"
I believe that this is correct JSON and it will parse in my app correctly.
The class I'm using in C# is as follows:
//[JsonObject(Title="team")] I tried adding this too
public class Team
{
public string Name { get; set; }
public List<Player> Players { get; set; }
}
Is this correct JSON and I need to fix my C# class? Or is it incorrect and how can I remove the column header from the json_agg output?
UPDATE:
Here's my table structure:
CREATE TABLE matches
(
id serial NOT NULL,
match json,
CONSTRAINT matches_pkey PRIMARY KEY (id)
)
And sample data:
5;{"Id":1,"Teams":[{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
6;{"Id":2,"Teams":[{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
Please see this question for more.