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

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

Linda Hamilton
Release: 2025-01-09 18:52:41
Original
327 people have browsed it

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

SQL to JSON conversion: Convert array of objects to array of values ​​in SQL 2016

SQL 2016 provides the function of converting SQL Server data to JSON, expanding many possibilities. However, when dealing with arrays of objects, sometimes the required JSON structure may differ from the default conversion result.

Specifically, when converting an array of objects to JSON, the default behavior is to embed the object as its own array within the parent array. For example:

<code class="language-sql">SELECT (SELECT item_id FROM #temp FOR JSON PATH,root('ids'))</code>
Copy after login

Result:

<code class="language-json">{
    "ids": [{
        "item_id": "1234"
    },
    {
        "item_id": "5678"
    },
    {
        "item_id": "7890"
    }]
}</code>
Copy after login

In some cases it may be preferable to display an array of objects as an array of values, without nested structures.

To achieve this, an intermediate XML transformation can be used:

<code class="language-sql">SELECT  
JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"' 
FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids  
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER</code>
Copy after login

This step converts the data into a flattened XML structure, which can then be converted to JSON using the JSON_QUERY() and WITHOUT_ARRAY_WRAPPER parameters. The result is the desired array containing the values:

<code class="language-json">"ids": [
        "1234",
        "5678",
        "7890"
    ]</code>
Copy after login

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

source:php.cn
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