SharadxDutta
SharadxDutta

Reputation: 1108

Nested JSON using ms sql server

I have a table with USER_DATA (user data table) with 2 rows (2 entries basically)

I created one nested JSON query ->

SELECT CONCAT( first_name,' ', last_name) AS displayName, 
       first_name AS givenName, last_name AS surname,
       identities = (SELECT login_name AS issuerAssignedId 
                       FROM user_data 
                        FOR JSON AUTO) 
 FROM user_data
  FOR JSON PATH, ROOT('users');

Here, I am getting this output ->

{
  "users": [
    {
      "displayName": "David Dave",
      "givenName": "David",
      "surname": "Dave",
      "identities": [
        {
          "issuerAssignedId": "System"
        },
        {
          "issuerAssignedId": "Administrators"
        }       
      ]
    },
    {
      "displayName": "Tony Padila",
      "givenName": "Tony",
      "surname": "Padila",
      "identities": [
        {
          "issuerAssignedId": "System"
        },
        {
          "issuerAssignedId": "Administrators"
        }
      ]
    }

But the problem is -> inside identities,

"issuerAssignedId": "System" ----> Belongs to Dave

"issuerAssignedId": "Administrators" ----> Belongs to Tony

But I am not able to stop the inner select query (Not able to map correctly)

The correct output should be --->

{
      "users": [
        {
          "displayName": "David Dave",
          "givenName": "David",
          "surname": "Dave",
          "identities": [
            {
              "issuerAssignedId": "System"
            }      
          ]
        },
        {
          "displayName": "Tony Padila",
          "givenName": "Tony",
          "surname": "Padila",
          "identities": [
            {
              "issuerAssignedId": "Administrators"
            }
          ]
        }

PLEASE HELP.

Upvotes: 0

Views: 72

Answers (1)

Sowmyadhar Gourishetty
Sowmyadhar Gourishetty

Reputation: 1878

You are missing the condition in the inner query and why do you want the identities to be a separate array in the JSON output.

I have updated the query as per my understanding please refer below sql, I'm not sure why you are having the ** in the query

     SELECT CONCAT (
        FIRST_NAME
        ,' '
        ,LAST_NAME
        ) AS displayName
    ,FIRST_NAME AS givenName
    ,LAST_NAME AS surname
    ,identities = (
        SELECT innr.LOGIN_NAME AS issuerAssignedId
        FROM USER_DATA
        innr
        WHERE
        innr.LOGIN_NAME = ottr.LOGIN_NAME
        FOR JSON AUTO
        )
   FROM USER_DATA ottr
   FOR JSON PATH
      ,ROOT('users');

Upvotes: 2

Related Questions