3

I am trying to concatenate nested JSON in SQL, how to do that.

Please help me out with this.

Example: I have JSON Like below.

    [
  {
    "Name": "Cards",
    "Value": [
      "Pack of 24 Dare Cards"
    ],
    "SourceSpecified": false,
    "Any": []
  },
  {
    "Name": "Boppers and Shot Glasses",
    "Value": [
      "12 Willy Shot Glass and 12 Hen Boppers"
    ],
    "SourceSpecified": false,
    "Any": []
  }
]

I want Out Put:

Pack of 24 Dare Cards-12 Willy Shot Glass and 12 Hen Boppers
2
  • Will Value only contain one element? Commented Aug 9, 2018 at 8:10
  • Yes only one element. Commented Aug 9, 2018 at 8:16

2 Answers 2

1

If Value always contains one element

DECLARE @JSON NVARCHAR(MAX) = '    [
  {
    "Name": "Cards",
    "Value": [
      "Pack of 24 Dare Cards"
    ],
    "SourceSpecified": false,
    "Any": []
  },
  {
    "Name": "Boppers and Shot Glasses",
    "Value": [
      "12 Willy Shot Glass and 12 Hen Boppers"
    ],
    "SourceSpecified": false,
    "Any": []
  }
]'

SELECT STRING_AGG(Val, '-')
FROM OPENJSON(@JSON)
WITH (Val NVARCHAR(MAX) '$.Value[0]')

Support of multiple values is also easy.

SELECT STRING_AGG(Val, '-')
FROM OPENJSON(@JSON)
WITH (VALUE NVARCHAR(MAX) '$.Value' AS JSON)
OUTER APPLY OPENJSON(VALUE) WITH (Val NVARCHAR(MAX) '$')
Sign up to request clarification or add additional context in comments.

6 Comments

'STRING_AGG' is not a recognized built-in function name
STRING_AGG need SqlServer 2017 as min version
You tagged sql-server-2017.
Sorry mine is sql server 2016
There are plenty of string join solutions prior SQL Server 2017. Just search it. I think your core question is json instead of string join.
|
1

This one I achieved with creating a scalar-valued function to populate concatenated value.

Create FUNCTION  [dbo].[test] 
(
    @VariationData nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN
                          Declare @val nvarchar(max)
                          select @val = COALESCE(@val+', ','')+ Value from  OPENJSON(@VariationData)
                          With ([Value] NVARCHAR(MAX) N'$.Value[0]') 
                          return @val

END

Call function with nested JSON value i.e

Select  [dbo].[test] (@JSON);

This worked for me.

Comments

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.