2

I have the following JSON and expecting a table out of it.

{
  "Response": [
    {
      "questionId": 1,
      "answer": [
        "5","6"
      ]
    },
    {
      "questionId": 2,
      "answer": [
        "5"
      ]
    }
  ]
}

And the expected table...

Table

I tried with the following, but didn't the exact output that i'm looking for.

SELECT QuestionId,Answer FROM OPENJSON(@responseJson, N'$.Response') r
 CROSS APPLY OPENJSON (r.value) WITH ( QuestionId   varchar(200)   '$.questionId', Answer nvarchar(max) '$.answer')
2
  • Welcome to SO. When posting a question, people expect you to ask a question (surprise! :) ). What is yours? What have you tried already to answer your question?
    – Thom A
    Commented May 9, 2018 at 10:42
  • possible duplicate of : stackoverflow.com/questions/37218254/… Commented May 9, 2018 at 11:05

1 Answer 1

3

Getting JSON into relational data is like peeling an onion. Use OPENJSON and CROSS APPLY until you've got all the layers you want. Use WITH to simplify the task of mapping values along the way.

SELECT questions.questionId, answers.answerId AS answer
FROM OPENJSON(@responseJson, '$.Response')
WITH (
    questionId INT,
    answer NVARCHAR(MAX) AS JSON
) AS questions
CROSS APPLY OPENJSON(answer)
WITH (
    answerId INT '$'
) AS answers;

There are shorter ways of writing this query, but I'd argue they're not as clear. (And if the execution plans are any indication, being explicit about the structure of the JSON using WITH helps with estimating memory requirements.)

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.