PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 19, 2022

[FIXED] How to split column headers & values in TSQL FOR JSON Option?

 May 19, 2022     for-json, json, tsql, web-services     No comments   

Issue

I have to talk to a webservice which accept JSON-messages, but is based on a dynamics princapel. so instead of using fixed defined fields, if wants a dynamics build, based on name\values attribute.

F.E.

{
    "Begin": [
        {
            "name": "sysrscols",
            "value": "sysrscols"
        },
        {
            "name": "id",
            "value": "3"
        },
        {
            "name": "crdate",
            "value": "2013-03-22T15:06:57.220"
        }
    ]
}

Using the FOR JSON option in SQL, I get a result with column names & their values. F.e. Query:

SELECT TOP 1 so.name,so.id,so.crdate  From sysobjects so FOR JSON PATH, Root('Begin')

Gives as result:

{
    "Begin": [
        {
            "name": "sysrscols",
            "id": 3,
            "crdate": "2013-03-22T15:06:57.220"
        }
    ]
}

How can I achieve the first result?


Solution

You'll need to unpivot your data here, and then use FOR JSON. I use a dirty solution here and convert the values to a sql_variant; I suggest you do not do thus. Instead CONVERT the values to a (n)varchar and use the appropriate style codes where needed to get the "format" you want.

I also bring your code into the mid 2000's, as the sys.sysobjects system view is a compatibility view for SQL Server 2000 (as noted in the documentation). As it's 2021, I felt it long past time you started using the "new" system objects:

SELECT V.name,
       V.value
FROM sys.objects so
     CROSS APPLY (VALUES(CONVERT(sql_variant,so.name),N'name'),
                        (CONVERT(sql_variant,so.object_id),N'object_id'),
                        (CONVERT(sql_variant,so.create_date), N'createdate'))V([value],[name])
WHERE so.[name] = 'SomeView' --This would be the object you want
FOR JSON PATH, ROOT('Begin');


Answered By - Larnu
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing