I have this query to append the arrary in JSON:
DECLARE @TheTable table(TheJSON nvarchar(max), Condition int ) DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}' INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1 UPDATE @TheTable SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}')) WHERE Condition = 1; SELECT TheJSON FROM @TheTable
It gives me the output in 1 single Row:
[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"},{"id": 3, "name": "Three"}]
Till this part it is correct.
Now I want to fetch the data from this table in rows and columns wise like a regular table:
ID Name 1 One 2 Two 3 Three
How to fetch the data from Json in rows and columns wise?
Any help would be appreciated
Advertisement
Answer
DECLARE @TheTable table(TheJSON nvarchar(max), Condition int ) DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}' INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1 UPDATE @TheTable SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}')) WHERE Condition = 1; SELECT @mystring = TheJSON FROM @TheTable SELECT p.* FROM OPENJSON (@mystring, '$') WITH(id varchar(10) '$.id', name varchar (30) '$.name') p