Home > Database > Mysql Tutorial > How to Convert a SQL Server Array of Objects to an Array of Values in JSON?

How to Convert a SQL Server Array of Objects to an Array of Values in JSON?

Barbara Streisand
Release: 2025-01-09 18:56:41
Original
1037 people have browsed it

How to Convert a SQL Server Array of Objects to an Array of Values in JSON?

SQL Server 2016 JSON Conversion: Transforming Object Arrays into Value Arrays

SQL Server 2016's JSON capabilities are powerful, but converting arrays of objects to arrays of values requires a specific approach. Let's illustrate the challenge and solution.

Consider this scenario:

CREATE TABLE #temp (item_id VARCHAR(256))

INSERT INTO #temp VALUES ('1234'),('5678'),('7890')

SELECT * FROM #temp

-- Initial JSON conversion attempt
SELECT (SELECT item_id 
FROM #temp
FOR JSON PATH,root('ids')) 
Copy after login

This yields a JSON array of objects:

{
    "ids": [{
        "item_id": "1234"
    },
    {
        "item_id": "5678"
    },
    {
        "item_id": "7890"
    }]
}
Copy after login

The goal, however, is a JSON array of values:

{
  "ids": [
    "1234",
    "5678",
    "7890"
  ]
}
Copy after login

The key is to leverage XML as an intermediate step:

SELECT  
JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"' 
FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids  
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER 
Copy after login

This query first constructs an XML string representing the values, then uses STUFF to remove the leading comma, and finally wraps the result in square brackets to form a JSON array. The FOR JSON PATH, WITHOUT_ARRAY_WRAPPER clause ensures the output is a single JSON array of values, not an array containing a single object. This efficiently achieves the desired JSON structure.

The above is the detailed content of How to Convert a SQL Server Array of Objects to an Array of Values in JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template