3

Want to prepare json without columns those are empty.

Here is detail example

MY_TABLE

=================
id ,   Name
=================
1  ,    Ali
2  ,    
3  ,    jhon
=================

SQL STATEMENT FOR JSON

(SELECT [Id],[Name] FROM My_Table)
FOR JSON PATH

SQL RESULT:

[{
    "Id": 1,
    "Name": "Ali"
}, {
    "Id": 2,
    "Name": ""
}, {
    "Id": 3,
    "Name": "Jhon"
}]

But i want to exclude element which has no value like No "Name":"" Element in following result:

[{
    "Id": 1,
    "Name": "Ali"
}, {
    "Id": 2,
}, {
    "Id": 3,
    "Name": "Jhon"
}]

EDITED: Please Note, i can apply CASE or UDF to convert empty values into null and null value may remove from json but it will slow the overall performance with large number of records therefore looking smart solution.

2
  • 1
    Can't you just add "... WHERE Name IS NOT NULL" in SELECT query? Commented Oct 4, 2018 at 9:49
  • i will lose id value if apply WHERE so it will not work Commented Oct 4, 2018 at 9:51

1 Answer 1

5

JSON Auto by default ignore the null fields if INCLUDE_NULL_VALUES not specified explicitly. Check for more info.

To include null values in the JSON output of the FOR JSON clause, specify the INCLUDE_NULL_VALUES option.

If you don't specify the INCLUDE_NULL_VALUES option, the JSON output doesn't include properties for values that are null in the query results.

Also, Sql Fiddle

Ignore Null Values

(SELECT [Id], (CASE WHEN Name = '' THEN NULL ELSE Name END) as Name FROM test)
FOR JSON Auto  

Include Null Values

(SELECT [Id],(CASE WHEN Name = '' THEN NULL ELSE Name END) as Name FROM test)
FOR JSON Auto, INCLUDE_NULL_VALUES
Sign up to request clarification or add additional context in comments.

6 Comments

there is no NULL value in my table but it empty string value in name to be ignored
you are right I can apply condition and it will work, but looking for smart/auto solution instead of adding condition on each field. My actual query contain list of many columns and large number of records and it will slow the performance if i apply case on each field. Yes I can create UDF instead of CASE to cover everything in once place but again UDF slow performance. you answer this is will be solution answer if i don't find any other smart solution.
Why don't you just make a SQL view with query for all needed fields as @mbharanidharan88 wrote and then select data from view for JSON?
@mbharanidharan88 answers your initial question. Either edit and expand your question or accept his answer.
I know this is an old post, but just in case someone else checks this out, you can replace the CASE statement that tests for an empty string to return null using NULLIF (e.g. NULLIF(Name, '') ).
|

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.