How to Remove Sequence Elements from JSON Output

muttBunch 120 Reputation points
2024-11-26T06:38:38.61+00:00

Hello all,

I am using the following code:

private class ArrayTest
{
    public int Count { get; set; }
    public double Time { get; set; }
}

public async Task<IActionResult> Get24HourLogonsById(int id, CancellationToken token)
{
	...

	var result = _applicationDbContext.Database
    	.SqlQueryRaw<ArrayTest>(query);
	var res = result.ToList();

	return new JsonResult(
    	res
	);
}

Which outputs as follows:


[
  {
    "count": 1,
    "time": 1732411589
  },
  {
    "count": 1,
    "time": 1732411592
  },
  {
    "count": 2,
    "time": 1732411600
  },
  {
    "count": 6,
    "time": 1732411625
  },
  {
    "count": 1,
    "time": 1732411649
  },
  {
    "count": 1,
    "time": 1732411652
  }...

I'd like to remove the titles "count" and "time" as well as switching the curly braces to square brackets for a format to use for Highcharts. I'd like the output to be:


[
  [
    1,
    1732411589
  ],
  [
    1,
    1732411592
  ],
  [
    2,
    1732411600
  ],
  [
    6,
    1732411625
  ],
  [
    1,
    1732411649
  ]
]

An example of Highcharts demo output: https://www.highcharts.com/samples/data/new-intraday.json

Any help would be appreciated,

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,128 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 47,976 Reputation points Microsoft Vendor
    2024-11-26T07:35:41.0733333+00:00

    Hi @muttBunch , Welcome to Microsoft Q&A,

    You can convert the data from a list of objects to a nested array format before returning the JSON result.

    public async Task<IActionResult> Get24HourLogonsById(int id, CancellationToken token)
    {
        var result = _applicationDbContext.Database
            .SqlQueryRaw<ArrayTest>(query);
    
        var transformedResult = result
            .Select(r => new object[] { r.Count, r.Time })
            .ToList();
    
        return new JsonResult(transformedResult);
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.