interkey
interkey

Reputation: 355

How to remove column name in JSON return C#

I have a JSON output below :

[
    {
        positionCode: "POS1",
        positionName: "POSITION 1",
        positionDescription: "",
        parentPosition: "POS2",
    },
    {
        positionCode: "POS2",
        positionName: "POSITION 2",
        positionDescription: "",
        parentPosition: "POS3",
    }
]

This JSON result is from my Web API that looks like this :

    return new JsonResult(query.Select(x => 
    new { x.PositionCode, x.PositionName , x.PositionDescription , x.ParentPosition }).ToList());

However, my desired output is like this :

enter image description here

What things should be done to achieve my desired result? In my javascript code or in my C# Web API? Thank you!

Upvotes: 2

Views: 1241

Answers (3)

Dave Anderson
Dave Anderson

Reputation: 12274

You are selecting an anonymous object with string properties when you want an array of the string values.

return new JsonResult(query.Select(x => 
    new string[] { 
       x.PositionCode, 
       x.PositionName, 
       x.PositionDescription, 
       x.ParentPosition 
    }).ToList()
);

Upvotes: 1

mwilson
mwilson

Reputation: 12900

Assuming you have a similar setup to this:

var data = new List<PositionClass>
{
    new PositionClass { PositionCode = "POS1", PositionName = "POSITION 1", PositionDescription = "", ParentPosition = "POS2" },
    new PositionClass {  PositionCode = "POS2", PositionName = "POSITION 2", PositionDescription = "", ParentPosition = "POS2" }
};

You have two options:

Handle it in your C# code

Looks like you already have linq, so just turn your List<T> into an array or strings:

data.Select(d => new[] {d.ParentPosition, d.PositionCode, d.PositionDescription, d.PositionName}).ToArray()

Handle it in your JavaScript code

const response = [{
    positionCode: "POS1",
    positionName: "POSITION 1",
    positionDescription: "",
    parentPosition: "POS2",
  },
  {
    positionCode: "POS2",
    positionName: "POSITION 2",
    positionDescription: "",
    parentPosition: "POS3",
  }
];

const reformatted = response.map(r => Object.values(r))

console.log(reformatted);

Upvotes: 2

Nikhil
Nikhil

Reputation: 6643

JavaScript's Object.values() can be used to do that.

var data = [{ positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION 2", positionDescription: "", parentPosition: "POS3", }]; 

var result = [];

data.forEach(item => {
  result.push(Object.values(item));
});

console.log(result);

Upvotes: 2

Related Questions