How can I query a table with key/value pairs into a JSON object using FOR JSON PATH?

Chad Gilbert

I have an Asset table and an Attributes table, where the attributes are simple key/value pairs.

DECLARE @Asset TABLE(AssetID INT)
INSERT @Asset VALUES (1)

DECLARE @Att TABLE (AssetID INT, Name NVARCHAR(100), Val NVARCHAR(100))
INSERT @Att VALUES (1, 'height', '100px'), (1, 'width', '200px')

I would like to write a query that groups by Asset and contains a column with the JSON representation of all attributes. For example:

AssetID      Attributes
------------ -----------------------------------------------
1            {"height":"100px","width":"200px"}

How can I write the query so that the attribute name value becomes the key in the resulting JSON object? When I use FOR JSON PATH, the keys are the column names:

SELECT
    AssetID,
    (
        SELECT Name, Val
        FROM @Att att
        WHERE att.AssetID = asset.AssetID
        FOR JSON PATH
    ) Attributes
FROM @Asset asset

which returns...

AssetID      Attributes
------------ -----------------------------------------------
1            [{"Name":"height","Val":"100px"},{"Name":"width","Val":"200px"}]
Pரதீப்

Am not sure about any native JSON methods to get the column data as Key in JSON. Alias names will be converted to key value in JSON.

So here is my try

You need to pivot the data to get the required key value pair format in JSON

If the key is static then

SELECT
    AssetID,
    (
        SELECT Max(CASE WHEN NAME = 'height' THEN Val END) AS height,
               Max(CASE WHEN NAME = 'width' THEN Val END) AS width
        FROM @Att att
        WHERE att.AssetID = asset.AssetID
        FOR JSON path, WITHOUT_ARRAY_WRAPPER
    ) Attributes
FROM @Asset asset

WITHOUT_ARRAY_WRAPPER is to remove the square brackets that surround the JSON output of the FOR JSON clause by default

Result:

+---------+--------------------------------------+
| AssetID |              Attributes              |
+---------+--------------------------------------+
|       1 | [{"height":"100px","width":"200px"}] |
+---------+--------------------------------------+

Since the key can be anything we need to use dynamic query to pivot the data

For demo I have changed the table variable to temp table

CREATE TABLE #Asset
  (
     AssetID INT
  )

INSERT #Asset
VALUES (1)

CREATE TABLE #Att
  (
     AssetID INT,
     NAME    NVARCHAR(100),
     Val     NVARCHAR(100)
  )

INSERT #Att
VALUES (1,'height','100px'),
       (1,'width','200px')

DECLARE @col VARCHAR(8000)= ''

SET @col = (SELECT ',Max(CASE WHEN NAME = ''' + NAME
                   + ''' THEN Val END) as ' + Quotename(NAME)
            FROM   #Att
            FOR xml path(''))
SET @col = Stuff(@col, 1, 1, '')

EXEC ('
SELECT
    AssetID,
    (
        SELECT '+@col+'
        FROM #Att att
        WHERE att.AssetID = asset.AssetID
        FOR JSON path, WITHOUT_ARRAY_WRAPPER
    ) Attributes
FROM #Asset asset') 

Result:

+---------+--------------------------------------+
| AssetID |              Attributes              |
+---------+--------------------------------------+
|       1 | [{"height":"100px","width":"200px"}] |
+---------+--------------------------------------+

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to convert comma separated Query param into KeyValue Pair json object using javascript

Deserialize json to list of KeyValue pairs

How I can define the @ symbol path on json_table oracle query

How do i parse json key value pairs inside a json object using volley andorid

How I can insert JSON web service data into a SQL table using SQL query?

How can i query the access object from JSON in CouchDB

How can I get the following query into a JSON object?

How can I parse JSON into a html table using PHP?

How can I print out multiple object in JSON using python?

How can I pull the object from the json using a key?

How Can I access JSON Object using flutter?

How can I include raw JSON in an object using Jackson?

How can I pass through a JSON object using an intermediate API?

How I can persist a json object using hibernate?

How can I cast JSON to a complex object using Typescript and Angular

How can I update a MongoDB collection using a JS/JSON object?

How can I get a JSON file into an object and display it using AngularJS?

How can I export a JSON object to Excel using Nextjs/React?

How can I extract these key/value pairs from this JSON node?

How can I JSON path without a values?

How can I get the Path value in this Json?

In Perl, how can query a JSON::Path object and return the paths of the matched elements?

JSON Objects in Swift 5 using Swift JSON, how can i make a JSON object like this :

How do I get all four keyValue pairs using RestAssured for CreateUser Post request

how can i get an object inside another object "JSON" using json-c?

How can I deserialize JSON to Java Object using GSON when the JSON using dates as property names?

How can i convert a plain JSON object to nested JSON Object

JAVASCRIPT: how can I remove a json object in json object?

How can I return a query result as JSON?

TOP Ranking

HotTag

Archive