1

I want to be able to return a JSON array of ids as part of a JSON object from SQL Server.

I have tried to get this to work and have come close but it is not the way I want the JSON to be structered.

This SQL I have outputs this

SELECT c.Pk_Company_Id AS [id],
       c.Name AS [name],
       r.Pk_Rig_Id AS [rigId]
FROM Company c
LEFT JOIN Rig r
ON c.Pk_Company_Id = r.Fk_Company_Id
FOR JSON PATH, ROOT('companies')

{"companies":[{"id":1,"name":"Company 1","rigId":100},{"id":1,"name":"Company 1","rigId":101},{"id":2,"name":"Company 2"}]}

This produces JSON that has everything I want kind of but I would like to structure rigIds as a JSON Array to produce something like this so i am not duplicating an object for no reason.

{"companies":[{"id":1,"name":"Company 1","rigIds":[100, 101]},{"id":2,"name":"Company 2"}]}

1 Answer 1

2

A variant with REPLACE:

SELECT
  c.Pk_Company_Id AS [id],
  c.Name AS [name],
  JSON_QUERY(REPLACE(REPLACE((SELECT r.Pk_Rig_Id id FROM Rig r WHERE c.Pk_Company_Id = r.Fk_Company_Id FOR JSON PATH),'{"id":',''),'}','')) [rigIds]
FROM Company c
FOR JSON PATH, ROOT('companies')

-- {"companies":[{"id":1,"name":"Company 1","rigIds":[100,101]},{"id":2,"name":"Company 2"}]}

A variant with STRING_AGG:

SELECT
  c.Pk_Company_Id AS [id],
  c.Name AS [name],
  JSON_QUERY((SELECT '['+STRING_AGG(r.Pk_Rig_Id,',')+']' FROM Rig r WHERE c.Pk_Company_Id = r.Fk_Company_Id)) [rigIds]
FROM Company c
FOR JSON PATH, ROOT('companies')
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, both work! I like the STRING_AGG solution.
Good luck! I also like the solution with STRING_AGG better. ))

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.