CarCrazyBen
CarCrazyBen

Reputation: 1136

SQL Server JSON_VALUE syntax

I created a SQL Server Table with 25 columns. One of my columns is actually JSON text, stored as nvarchar(max).

Now I need to able to query this JSON column and parse out the various attributes. I have tried applying JSON_VALUE to my column but am doing something wrong; my query runs but returns NULL for all the values.

The JSON itself looks like:

[
 {
  "lineName":"GHjr",
  "pipeDiameter":"12",
  "pipeLength":"52000",
  "pressure":"15",
  "volume":"107"
 },
 {
  "lineName":"Ks3R",
  "pipeDiameter":"9",
  "pipeLength":"40000",
  "pressure":"15",
  "volume":"80"
 }
]

The SQL I am using is:

select
 DOC_ID, LINE_SPECS,
 JSON_VALUE(LINE_SPECS, '$.lineName')     as line_name,
 JSON_VALUE(LINE_SPECS, '$.pipe_Diameter') as diameter
from dbo.MY_TEST_DOCS
where ISJSON(LINE_SPECS) > 0
  and len(LINE_SPECS) > 3

However, my 2 "parsed" columns are returning all NULL. How do I parse the five attributes from this column?

Upvotes: 8

Views: 23285

Answers (1)

Paul Maxwell
Paul Maxwell

Reputation: 35603

Without the [] ISJSON is returning false
With [] ISJSON retuns true
Without the [] JSON_VALUE returns NULLs
With [] JSON_VALUE returns values

dbfddle.uk has sql server 2016 available....

create table test (LINE_SPECS nvarchar(max));

insert into test values (N'
 {
  "lineName":"GHjr",
  "pipeDiameter":"12",
  "pipeLength":"52000",
  "pressure":"15",
  "volume":"107"
 },
 {
  "lineName":"Ks3R",
  "pipeDiameter":"9",
  "pipeLength":"40000",
  "pressure":"15",
  "volume":"80"
 }
');

select * 
from test
where ISJSON(LINE_SPECS) > 0
;

GO
| LINE_SPECS |
| :--------- |
select
      JSON_VALUE(LINE_SPECS, '$.lineName')     as line_name
    , JSON_VALUE(LINE_SPECS, '$.pipeDiameter') as diameter
from test
;
GO
line_name | diameter
:-------- | :-------
GHjr      | 12      

dbfiddle here

Upvotes: 6

Related Questions