简体   繁体   中英

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM