1

When I run this I get an error how do I take into consideration that the value could be null and it not throw a error ?

       declare @Concepts varchar(500)

    set @Concepts = '{"Concepts":null}';

   select [value] from openjson(@Concepts,'strict $.Concepts')

when it is not null

    set @Concepts = '{"Concepts": [4324,2342]}';

This is the error I am getting

Value referenced by JSON path is not an array or object and cannot be opened with OPENJSON.

4
  • What is the error you're getting? A null reference exception using the result of the query, or an error parsing/running the query? Please note that NULLs behave differently in SQL than most other languages (e.g. do not try X = NULL instead do X IS NULL and X IS NOT NULL instead). Commented Jan 16, 2019 at 15:04
  • Value referenced by JSON path is not an array or object and cannot be opened with OPENJSON. is the error understand they behave differently I am more talking about where there is a null in my JSON Commented Jan 16, 2019 at 15:06
  • What's Concepts supposed to be when it's not null? The correct answer depends on whether it's another JSON object or a scalar value. Commented Jan 16, 2019 at 15:12
  • I updated my question Commented Jan 16, 2019 at 15:14

1 Answer 1

2

I figured out taking the string 'strict' out of 'strict $.Concepts' solved my issue

 declare @Concepts varchar(500)
 set @Concepts = '{"Concepts":null}';
 select [value] from openjson(@Concepts,'$.Concepts')
2
  • Jeez. Now I feel silly... I missed this because I tested with {"Concepts":3}. In that case this approach won't work because it will not return any rows. (Neither will my suggested answer, though, which will henceforth be deleted.) The one thing of note is that the omission of strict means this query will succeed even if the Concepts property is missing entirely, which may or may not be what you want. Commented Jan 16, 2019 at 15:30
  • I appreciate your help in my scenario I don't care if it is missing entirely I am new to JSON and SQL server so any help I can get is appreciated. Commented Jan 16, 2019 at 15:37

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