Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server JSON_VALUE syntax

Tags:

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?

like image 683
CarCrazyBen Avatar asked Nov 08 '17 21:11

CarCrazyBen


1 Answers

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

like image 123
Paul Maxwell Avatar answered Nov 15 '22 13:11

Paul Maxwell