Reputation: 33
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}]}
Upvotes: 3
Views: 4111
Reputation: 1530
If the response is in OData format, as your example shows, but you want it in JSON format that can be parsed by JSON.parse, add $format=json to the OData query, so long as the OData endpoint supports it. I know Dynamics 365 does not.
Upvotes: 0
Reputation: 904
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....
Upvotes: -1
Reputation: 943548
The problem is the response is formatted as an array instead of JSON
It can't be. You can't send "an array" over HTTP. You have to encode it somehow … e.g. as JSON.
jQuery will, unless you override it with the dataType
option, use the Content-Type
HTTP response header to determine how the data is encoded. If it is JSON, it will parse the JSON.
The value of data
is what you would get if you read the raw responseText
and passed it through JSON.parse
.
So just don't try to parse it manually. jQuery has done it for you.
Skip the step:
var jsonData = JSON.parse(data);
… and just work with data
.
NB: The output of JSON.parse
is an object, array or other JavaScript data type. JSON data is what you get from JSON.stringify
.
Upvotes: 2