1

I have this content in a table in a column JsonResponse:

{
  "results": {
    "meta": {
      "number_of_node": 2
    },
    "data": {
      "Node": [
        {
          "id": "44511",
          "subject": 31366
        },
        {
          "id": "72176",
          "subject": 36508
        }
      ],
    }
  }
}

I'm trying to extract ALL the "subject"; here my query:

SELECT 
    JSON_VALUE(JSonResponse, '$.results.data.Node.subject') AS JsonResponse
FROM
    Table

but the query result is always null.

I didn't find documentation about querying nested Json, any tips?

Thanks!

2
  • Did you have a look at OPENJSON? Commented Sep 6, 2022 at 12:41
  • 1
    SQL Server 2014 has no support for JSON. There are workarounds/hacks, but they're all painful. The best approach if you can't upgrade (which is recommended, since SQL Server 2014 has been out of support for 3 years now) is to leave the JSON parsing to the client side. Commented Sep 6, 2022 at 15:42

2 Answers 2

1

Try this:

DECLARE @Table TABLE (
    JSonResponse NVARCHAR(MAX)
);
INSERT @Table ( JSonResponse )
VALUES (
'{
  "results": {
        "meta": {
          "number_of_node": 2
        },
        "data": {
          "Node": [
            {
              "id": "44511",
              "subject": 31366
            },
            {
              "id": "72176",
              "subject": 36508
            }
          ]
        }
  }
}'

    );

SELECT oj2.*
FROM @Table AS t
     CROSS APPLY
    OPENJSON(t.JSonResponse, '$.results')
        WITH ( meta NVARCHAR(MAX) AS JSON, data NVARCHAR(MAX) AS JSON ) AS oj
     CROSS APPLY
    OPENJSON(oj.data, '$.Node')
        WITH ( id INT, subject NVARCHAR(MAX)) AS oj2;
Sign up to request clarification or add additional context in comments.

Comments

1

You don't necessarily need nested OPENJSON calls, as you can jump straight to the right path

SELECT oj.*
FROM @Table AS t
CROSS APPLY OPENJSON(t.JSonResponse, '$.results.data.Node')
  WITH (
    id int,
    subject int
  ) AS oj;

db<>fiddle

4 Comments

I've got this: Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Are you still running SQL Server 2014? Then this won't work, you should upgrade to a newer version
I can't upgrade :(
Only other option I can think is to write a SQLCLR function that uses Newtonsoft or similar to parse it. Or parse it client-side and send it as a Table Valued Parameter

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.