2

I have a Web-API method that is returning JSON and I want the array structure to look like this: [ [123, 1.1], [222, 3.9] ]

My Web API controller is returning JSON in the following format: [{"CreatedDate":1314736440,"Reading":20.0}, "CreatedDate":1314779640,"Reading":7.9}]

Web API Controller:

[HttpGet]
 public HttpResponseMessage AllJson()
 {
     using (var ctx = new SomeContext())
     {
         var records = ctx.DataX.ToList();
         var dtos = Mapper.Map<...>(records);
         return new HttpResponseMessage
         {
             StatusCode = HttpStatusCode.OK,
             Content = new StringContent(JsonConvert.SerializeObject(dtos), Encoding.UTF8, "application/json")
         };
     }
 }

DTO

public class DtoModel
    {
        public int CreatedDate { get; set; }
        public double Reading { get; set; }
    }

Sample Javascipt:

var seriesData = [];
        $.getJSON("api/xxx/AllJson ", function (data) {
            $.each(data, function (key, val) {
                seriesData.push(val.CreatedDate.toString() + " ," + val.Reading.toString());
                console.log(val.CreatedDate + " ," + val.Reading);
            });
        });

2 Answers 2

1

You need to create an a single array containing many arrays of length 2.

See this code:

 $.getJSON("api/xxx/AllJson")
            .done(function (data) {
                var processedJson = new Array();
                $.map(data, function (obj, i) {
                    processedJson.push([obj.CreatedDate, obj.Reading]);
                });

                FunctionToDoSomethingWithYourDataStructure(processedJson);
            });
Sign up to request clarification or add additional context in comments.

Comments

0

I think this might solve your problem.. structure wise, this should look like [[a,b],[c,d]];

var createSeriesData = function(){
    seriesData = [];
    JSON_obj = JSON.parse('[{"CreatedDate":1314736440,"Reading":20.0},{"CreatedDate":1314779640,"Reading":7.9}]');

    for(var key in JSON_obj){
        if(JSON_obj.hasOwnProperty(key)){
            seriesData[key] = [];
            seriesData[key].push(JSON_obj[key].CreatedDate.toString());
            seriesData[key].push(JSON_obj[key].Reading.toString());
        }

    }

    console.log(seriesData);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.