Javascript ajax result not able to split - javascript

I am using javascript. The following is object from jax response,
{"readyState":4,"responseText":"\r\nsuccess","status":200,"statusText":"OK"}
and my code is,
complete: function(data)
{
//console.log(data);
var result_act = JSON.stringify(data);
alert(result_act);//returning above object
var resp = result_act.responseText;//Returning undefined
}
now i want to get the responseText from this object. Any help much appreciated!

Instead of JSON.stringify you need JSON.parse
parse will parse the incoming JSON string into appropriate Javascript object. stringify is the opposite action - Javascript object into JSON valid string.

// When your server response comes with full qualified parsed JSON, it may access without any parsing.
var data, resp;
data = {"readyState":4,"responseText":"\r\nsuccess","status":200,"statusText":"OK"};
resp = data.responseText;
console.log("Response as JSON object >",resp);
// When your server response comes with JSON as string, then you require to first parse then you may allows to access.
data = '{\"readyState\":4,\"responseText\":\"\\r\\nsuccess\",\"status\":200,\"statusText\":\"OK\"}';
data = JSON.parse(data);
resp = data.responseText;
console.log("Response after parsing JSON >",resp);

Related

Google App Script throws Unexpected token e in JSON at position 0 but only sometimes

One answer for post request said to stringify the JSON payload, but I am sending a get request
var list= [ "bitcoin","ethereum","litecoin","dogecoin","stellar","cardano","tezos","0x","uniswap"]
var url = "https://api.coingecko.com/api/v3/simple/price?ids="+list.join(",")+"&vs_currencies=usd"
var headers={ "accept": "application/json", "muteHttpExceptions":true}
var response = JSON.parse(UrlFetchApp.fetch(url,headers));
Logger.log(response)
The error occurs at line 4.
I thought maybe I should stringify the headers , so I did JSON.parse(UrlFetchApp.fetch(url, JSON.stringify(headers))) But it raised the exception Bad Value at this same line
The problem is that, the initial code is running fine for most of the times, but sometimes it raises that exception
This is because you have the response object and not the string data..
var response = JSON.parse(UrlFetchApp.fetch(url,headers));
//to:
var response = UrlFetchApp.fetch(url,headers);
var data = JSON.parse(response.getContentText());

Is there a way to tell if a POST (body) request is formatted as a URL encoded query string or JSON data?

I am writing the server side code to handle incoming post requests (using NodeJS and Express).
If the request coming into the server is formatted as JSON data, then I want to use JSON.parse, but if the data coming in is formatted as a URL encoded query string, then using JSON.parse on that data gives me the error below. Any suggestions? Code at the bottom.
app.post("/", (req, res) => {
let parsedData;
// if request.body is received as JSON data, I want to put it inside the loop below and parse it and then set parsedData equal to that parsed data.
// if the request.body is received as url encoded data, I just want to set parsedData = req.body
for (var key in req.body) {
parsedData = JSON.parse(key);
}
})
Actually I was able to figure it out! Basically I created a separate function to see if I could JSON PARSE the req.body
function isJSONObject(value) {
try {
JSON.parse(value)
} catch {
return false;
}
return true;
}

Sending JSON from backend to frontend

I need some clarification on JSON objects. Inside my node backend, I receive a JSON object and after I'm done going through which key/value pairs I need, I send it off to the frontend. This is where I'm getting confused- I still need to turn that response object into json via response.json(). Why? If the backend is passing JSON, then why would I need to turn the response obj into JSON?
// test.js (node)
const testObj = {
"test1": {
"1": "Hello there"
}
}
app.get('some-route', async(req,res) =>{
res.send(testObj)
}
// front.js (React)
async someFunc(){
const response = await fetch('/some-route');
const data = await response.json(); //why?
}
Because on your front-end, the fetch API receives a buffer -- an array of bytes, which could contain any payload. It could be an image, plain text, a file, or a JSON payload.
Knowing what your back-end is going to send down, you need to receive the buffer of the data and then perform the .json() API on it, essentially asking that the buffer be interpreted as a serialized string representing a JSON object, and then having the Javascript engine evaluate (deserialize) that string into an object.
Fetch is a multi-purpose API that doesn't have any prior knowledge about the payload that the server is going to send. You are instructing it to treat the payload as JSON by using the .json() function.
Besides .json(), there are other helper methods to read and parse a variety of other possible response types; for example, .text() for plain text, .formData() for form encoded data (similar to querystring values), .blob(), and .arrayBuffer() for byte-level access to the returned data. You will use the appropriate method based on the response type that you're expecting from the API.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
The response object isn't whatever you sent from the backend, it will be a Response object. That's how the Fetch API works. That Response object will have lots of metadata on it, and some methods, including .json which Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
If you don't want to have to go through these two steps, just write this function.
const fetchJson = async url => {
const response = await fetch(url)
return response.json()
}
and use it like this:
async someFunc(){
const data = await fetchJson('/some-route')
}
A response object is more than just its JSON part. It contains all HTTP protocol elements, like headers, the state of the response and so on.
When you use res.json() you are telling your code to separate only the JSON part from all these other things.
To understand a bit more about an HTTP response, I suggest you to read this.
Good question!
When you send data to the front-end from the back-end, you're not just sending the data payload you created in your testObj. What's actually being returned is a response object, which will look something like:
{
type: "cors",
url: "http://some-url.com/some-api",
redirected: false,
status: 200,
ok: true,
body: ReadableStream,
...
headers: Headers,
json: json(),
...
}
where the value of response.json is the body deserializer method in the response object. You can see for yourself; try to console.log(data) from your example after removing the .json() bit, and you'll get a look at the response object in its entirety.
As you can see, the response's body - or the payload you sent from the server - is received by the client as a ReadableStream object, which then needs to be deserialized once the entire object has reached the client. The response.json() method simply deserializes the response.body ReadableStream object from serialized byte data into JSON, which you can then parse in your application.

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}]}
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.
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.
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....

JSON response from Python json.dumps

I am trying to send a Django HttpResponse encoded as JSON to Javascript.
Python:
response_data = {}
response_data['status'] = 'incomplete'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Jquery:
function auth_request(){
$.ajax({
url: AUTH_ENDPOINT + "myid0001",
context: document.body,
success: function(response){
console.log(response);
console.log(response.status);
if(response.status == "incomplete"){
//do something here
}
}
}
});
}
The console prints {"status": "incomplete"} for the first console log and undefined for the console.log function accessing the status element.
I tried using JSON.parse(response) but I get the error
Uncaught SyntaxError: Unexpected token a in the jquery.js file which I believe is indicating that the object is already a JSON object. However, if I check the type of the object, it displays string. How can I access the elements of the response JSON object?
You need to parse the Json back into a JS object when it's received. Otherwise, it's just text.
jQuery will do that for you if you specify dataType: "json" in the Ajax call.
I found the solution. It turns out that my Django setup was returning some additional string items so when I tried to set dataType: "json" (as #Daniel Roseman suggested) or in the jQuery function or use JSON.parse(response) I received an error. I was able to remove the extra string and it worked properly.

Categories

Resources