0

In SQL Server 2016 +, how can i convert a table looking like this:

+---------+----------+
|   Kee   |   Val    |
+---------+----------+
| aaaaaa  | 11111111 |
| bbbbbbb |  2222222 |
+---------+----------+

into an object looking like this:

{
  "aaaaaa": "11111111",
  "bbbbbbb": "2222222"
}

This is what I've tried:

CREATE TABLE #tmp
(
    Kee VARCHAR(100),
    Val VARCHAR(100)
)
INSERT INTO #tmp
(
    Kee,
    Val
)
VALUES
('aaaaaa', '11111111'),
('bbbbbbb', '2222222')


SELECT t.Kee,
       t.Val
FROM #tmp AS t
FOR JSON AUTO
DROP TABLE #tmp

But it gives:

[
  {
    "Kee": "aaaaaa",
    "Val": "11111111"
  },
  {
    "Kee": "bbbbbbb",
    "Val": "2222222"
  }
]
2
  • What you're asking for is not valid JSON. Commented Jul 16, 2019 at 15:25
  • 1
    @JAAulde yikes, typo, fixed, thanks! Commented Jul 16, 2019 at 15:34

1 Answer 1

2

Unfortunately, SQL Server's Json support is not that flexible.
You will have to manually construct that json, but it's quite simple using basic string concatenation techniques.

Prior to 2017 version use for xml path with stuff:

SELECT STUFF(
    (
        SELECT '","'+ t.Kee +'":"'+ t.Val
        FROM #tmp AS t
        FOR XML PATH('')
    ), 1, 2, '{') + '}' As JsonResult

In 2017 SQL Server finally introduced a built-in string_agg function, making the code required to get that result much simpler:

SELECT '{"' + STRING_AGG(t.Kee +'":"'+ t.Val, '","') +'"}'
FROM #tmp As t

Result (in both cases):

{"aaaaaa":"11111111","bbbbbbb":"2222222"}     
Sign up to request clarification or add additional context in comments.

7 Comments

What you have produced is what the OP asked for, but is not valid JSON.
The structure, ["key":"value"], is not JSON. {"key":"value"} is JSON
@JAAulde You are correct - but that, as you wrote, what the OP has asked for. An easy change in the code will provide a valid json, if that's needed. (simply change the [ to { and ] to }.)
Guys, sorry i mis-typed my output JSON {"aaaaaa":"11111111","bbbbbbb":"2222222"} is what Im looking for. Thanks!
@JAAulde after the OP have edited the question, I've reedited the answer.
|

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.