5

JSON stored in a column 'DataJson' in table

[{
    "KickOffDate": "1-Jan-2019",
    "TeamSize": "11",
    "ClientEngineer": "Sagar",
    "WaitingPeriod": "16.5"
}]

Query

SELECT JSON_VALUE(DataJson,'$.KickOffDate') AS KickOffDate
     , JSON_VALUE(DataJson,'$.ClientEngineer') AS ClientEngineer
FROM [ABC].[Deliver]

Result

KickOffDate   ClientEngineer
NULL          NULL

Result should be:

KickOffDate   ClientEngineer
1-Jan-2019    Sagar
Salman A
  • 262,204
  • 82
  • 430
  • 521
Gibin Jacob Job
  • 59
  • 1
  • 1
  • 3

2 Answers2

12

Your sql query is wrong.
You have to correct query like below.

 SELECT JSON_VALUE(DataJson,'$[0].KickOffDate') AS KickOffDate ,JSON_VALUE(DataJson,'$[0].ClientEngineer') AS ClientEngineer FROM [ABC].[Deliver]

The data stored in table is not JSON Object, it's JSON Array.
So in order to get each value of JSON Object, need to set index of JSON Object in JSON Array.
Otherwise, you can store data as JSON Object, and then your query can be work normally.

mark Oriend
  • 165
  • 10
2

Your JSON appears to be malformed, at least from the point of view of SQL Server's JSON API. From what I have read, if your JSON data consists of a top level JSON array, then the array needs to have a key name, and also the entire contents should be wrapped in { ... }.

The following setup has been tested and works:

WITH yourTable AS (
    SELECT '{ "data" : [{"KickOffDate": "1-Jan-2019", "TeamSize": "11", "ClientEngineer": "Sagar", "WaitingPeriod": "16.5"}] }' AS DataJson
)

SELECT
    JSON_VALUE(DataJson, '$.data[0].KickOffDate') AS KickOffDate,
    JSON_VALUE(DataJson, '$.data[0].ClientEngineer') AS ClientEngineer
FROM yourTable;

enter image description here

Demo

Here is what the input JSON I used looks like:

{
    "data" : [
        {
            "KickOffDate": "1-Jan-2019",
            "TeamSize": "11",
            "ClientEngineer": "Sagar",
            "WaitingPeriod": "16.5"
        }
    ]
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360