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

How to Extract an Array of Values from an Array of JSON Objects in SQL Server 2016?

Patricia Arquette
Release: 2025-01-09 18:41:42
Original
919 people have browsed it

How to Extract an Array of Values from an Array of JSON Objects in SQL Server 2016?

SQL Server 2016: Transforming JSON Object Arrays into Value Arrays

SQL Server 2016's JSON capabilities are robust, but extracting specific data structures sometimes requires creative approaches. This example demonstrates transforming a JSON array of objects into a simpler array of values.

The Challenge:

Consider a query that generates a JSON array of objects:

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

This yields JSON like this:

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

The goal is to restructure this into a JSON array containing only the item_id values:

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

The Solution:

The key is a two-step process leveraging XML as an intermediary:

<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 code first uses FOR XML PATH('') to concatenate the item_id values, surrounding each with double quotes. STUFF removes the leading comma. The result is then wrapped in square brackets to create a valid JSON array, which JSON_QUERY parses. Finally, FOR JSON PATH, WITHOUT_ARRAY_WRAPPER formats the output as a simple JSON array. This effectively flattens the original JSON object array into the desired value array.

The above is the detailed content of How to Extract an Array of Values from an Array of JSON Objects in SQL Server 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