Retrieve numerous rows by utilizing the forthcoming SQL Server TSQL command for extracting data from JSON format

I'm attempting to fetch multiple rows using the SQL Server 2017 TSQL code from a JSON object.

DECLARE @json NVARCHAR(MAX);
SET @json = N'{
  "DateCreated": "2020-08-02T16:04:59.3558001+01:00",
  "Name": "Bolts",
  "Price": 123.45,
  "Length": 15.7,
  "Quantity": 1,
  "Attributes": [
    {
      "AttrHeading": "Material",
      "AttrVal": "Steel"
    },
    {
      "AttrHeading": "Colour",
      "AttrVal": "Black"
    },
    {
      "AttrHeading": "Finish",
      "AttrVal": "Matt"
    }
  ]
}';

SELECT j.*
FROM OPENJSON (@json, N'$')
  WITH (
    
    DateCreated datetime2 N'$.DateCreated',
    [Name] varchar(100) N'$.Name',
    Price decimal(19,4) N'$.Price',
    [Length] decimal(19,4) N'$.Length',
    Quantity integer N'$.Quantity',
    AttrHeading varchar(max) N'$.Attributes.AttrHeading',
    AttrVal varchar(max) N'$.Attributes.AttrVal'
  ) AS j;

I am hoping for three distinct rows to be returned, each one representing an attribute. This means that the other details like Name, Price, Length will remain the same for each row, only changing for AttrHeading and AttrValue.

As of now, AttrHeading and AttrVal are showing as null - is there any way to resolve this?

Answer №1

To properly handle the nested array in this scenario, you'll need to utilize OPENJSON() twice: once for the outer object (where the nested array should be stored in a JSON column), and a second time to unnest the array:

SELECT j.DateCreated, j.Name, j.Price, j.Length, j.Quantity, x.*
FROM OPENJSON (@json) WITH (
    DateCreated datetime2,
    Name        varchar(100),
    Price       decimal(19,4),
    Length      decimal(19,4),
    Quantity    integer,
    Attributes  nvarchar(max) AS JSON
) AS j
OUTER APPLY OPENJSON(j.Attributes) WITH (
    AttrHeading varchar(max),
    AttrVal     varchar(max)
) x;

The query has been optimized by eliminating redundant column names and paths for improved readability.

Check out the live demo on DB Fiddle:

DateCreated                 | Name  |    Price |  Length | Quantity | AttrHeading | AttrVal
:-------------------------- | :---- | -------: | ------: | -------: | :---------- | :------
2020-08-02 16:04:59.3558001 | Bolts | 123.4500 | 15.7000 |        1 | Material    | Steel  
2020-08-02 16:04:59.3558001 | Bolts | 123.4500 | 15.7000 |        1 | Colour      | Black  
2020-08-02 16:04:59.3558001 | Bolts | 123.4500 | 15.7000 |        1 | Finish      | Matt   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to combine the existing array data with the previous array data in JavaScript?

I am implementing server-side pagination in my MERN project. Let's say I retrieve 100 products from the database and want to display only 30 products, with 10 products per page. When a user navigates to the 4th page, I need to make another API call to ...

Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm: The result of my json_encode() operation in the ...

The function json.stringify fails to invoke the toJson method on every object nested within the main object

When using IE 11, I encountered an issue where calling Stringify on my objects did not recursively call toJson on all objects in the tree. I have implemented a custom toJson function. Object.prototype.toJSON = function() { if (!(this.constructor.name == ...

Encountered an issue with logging the "render_template.action_view" event after upgrading Rails to version 4.2.8

I'm currently in the midst of upgrading a rails application that primarily deals with serving JSON. The latest version I successfully upgraded to was 4.1. However, upon attempting to upgrade to version 4.2, I began encountering peculiar errors in the ...

Contrast the dissimilarities between JSON and alternative errors

encoder := json.NewEncoder(writer) error := encoder.Encode(struct { RequestMethod string `json:"request_method"` QueryResults []interface{} `json:"query_results"` TimeInCache int `json:"time_in_cache"` }{RequestMethod: pro ...

Exploring how to display JSON objects containing spaces in an HTML table

Sorry if this question has been asked already, but I can't find the answer. I'm brand new to html/java/django and struggling with a seemingly simple issue. I am developing a web application that retrieves json data from firebase using python/pyre ...

Use the `DefaultValue` feature on all string properties during serialization

Make sure to set DefaultValue for all string properties. Situation: The classes below are automatically generated, making it tedious to manually add properties. To simplify the process, I created a program that uses regex to add the necessary properties ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

Access information from a JSON string using C#

I am new to working with JSON, and I have received the following JSON string. I am looking to extract the IDs in the format 1,2,6,3,5,4 (getting the id object with comma separation) using ASP.NET with C#. [ { "id":1, "children": [ ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

Decoding GeoJSON: Extracting a feature from an array

I am currently working on a map project where I am drawing polygons with properties pulled from a JSON file. Each polygon is colored based on feature values in the JSON file. Here's an example of a feature in the JSON file: { "type": "Feature", " ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

Generating a compilation from a variety of JSON documents

I have a goal to compile a corpus containing the content of various articles stored in JSON format. These articles are spread across different files named after the year they were published; for instance: with open('Scot_2005.json') as f: da ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

Guide on including a sum (integer) property in the JSON output of my API

Currently, I am working on an API using Express.js. In one of my functions named getAll, my goal is to not only return an array of records but also include the total number of records in the response. The code snippet below showcases how I have been handli ...

What is the best way to execute a SQL query within a JavaScript loop or map function?

I have a task at hand: Iterate through an array of objects using the map function Execute multiple SQL queries based on each object Append the query results to the respective objects The array I'm looping through contains offers, which are objects w ...

Deciphering JSON information in RAILS 3.0.6 that is provided via an HTTP POST request using the content-type application/x-www-form-urlencoded

Upon receiving an HTTP POST from a third party with content-type specified as 'application/x-www-form-urlencoded' in my RAILS 3.0.6 controller, I attempted to parse the request in two ways: Firstly, by accessing the status parameter like so: job ...

JSON function invocation is failing to load

This is my JavaScript script, When I call the function calculate(), the JSON method ConvertDataTabletoString() only gets called once, when I load the page. I want the method to be called every 5 seconds. I am calling a VB.NET function in .aspx. How can ...

Checkboxes within Angular's reactive forms are a powerful tool for creating dynamic user

Currently, I am working on a contact form that includes checkboxes for users to select multiple options, with the requirement of selecting at least one box. My challenge lies in figuring out how to pass all the selected checkboxes' data to an API usin ...