If I have a graph with this kind of structure:
@prefix : .
@prefix rdf: .
You're conflating the query result itself (essentially an abstract table structure) with the syntax in which that result is written (in your case, a customized nested JSON structure).
Don't try to do tricks with group concatenation in this case. Just do this query:
SELECT ?given ?family ?friend_given ?friend_family
WHERE {
?person foaf:givenName ?given ;
foaf:familyName ?family .
?person :knows ?friend .
?friend foaf:givenName ?friend_given ;
foaf:familyName ?friend_family .
}
GROUP BY ?family ?given
Which results in a result like this:
given family friend_given friend_family
--------------------------------------------
Alice Lidell Bob Doe
Alice Lidell Hwa Choi
And then let a custom streaming result writer write the result to the nested syntax format you require. Given that the query groups by name, the writer can safely assume that subsequent rows with the same given and family names "belong together".
Alternatively, use a CONSTRUCT query instead of a SELECT, and post-process the retrieved RDF graph (which accurately represents the tree structure you're after).