Search code examples
javascriptjsonodata

OData returns array instead of JSON - How to convert?


I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.

My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?

Here is the code that I am using:

$.ajax({
                type: "GET",
                url: requestUri,
                dataType: "script",
                accept: "application/json",
                success: function(data, request) {
                    var jsonData = JSON.parse(data);
                },
                error: function(msg) {
                    alert(msg);
                }})

Here is an example response of logging the variable data with console.log:

{"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}


Solution

  • You can add it to a variable and access it just like that.

    var v={"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]};
    //v.value[0] is a json object
    console.log(v.value[0]);
    

    or skip the assignment altogether and access this way:

    data.value[0]
    data.value[0].Genre
    data.value[0].RunTime
    etc....