try to get the value of json object - javascript

I have an ajaxpost that returns a response in form of json and I want to show the message
{ "TEXT" : "Please fix it. there might be otehr reason, and need to address it, or call, incorrect username/password-username/port?. " }
How can I get the value of json? I used the following but Message is undefined, What are the other ways of getting json object
var TEXT = text.resp;

Include this library and below code to parse your json
var json = $.parseJSON(obj.responseText);
var msg = json.message;
You can also try below code
var json = JSON.parse(obj.responseText);
var msg = json.message;

You should try to parse the object and then access it with json["object"] instead of the dot.

Related

Can't call a part of an object after parsed as JSON in Google Apps Script

I'm trying to make some code that can pull from an API and pull out a piece from the response. My code is below.
var response = UrlFetchApp.fetch('https://[API_URL]', options);
Logger.log(response.getContentText());
var firstCall = response.getContentText();
var JsonObj = JSON.parse(firstCall);
Logger.log(firstCall['id']);
sheet.appendRow(['successfully connected to API.']);
sheet.appendRow([Logger.getLog()]);
A sample response from the API is below.
[{"id":12345678901234567,"name":"email#email.com - someText"}]
When I try to run the first code, it completes the code, logging the above line and undefined. My goal is to get just the ID from the string. Thanks for your help!
You're almost there. To keep it simple, do it like this:
function getURLFromSite(){
var response = UrlFetchApp.fetch('https://jsonplaceholder.typicode.com/users');
var JsonObj = JSON.parse(response);
Logger.log(JsonObj[1].name);
}
Here's JsonObj is like an array which you can access using JsonObj[0], JsonObj[1] and JsonObj[2].
To access properties like id or name, just use the dot notation like JsonObj[0].id or JsonObj[1].name.

Getting error when trying to return value to javascript

Im trying to return a value back to dropzone's javascript on success. Im using a return Json action and trying to build a url to direct to another view. My question, How do I return a value back to a javascript function and get the value?
Im getting an error like this when i try to find the value.
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at u.<anonymous> (Upload:44)
at u.n.emit (dropzone:1)
at dropzone:1
when my code is like this:
myDropzone.on("queuecomplete",
function(data) {
this.removeAllFiles();
var res = JSON.parse(data);
var url = "#Url.Action("OrderConfirmation","Upload", new
{
OrderNumber = "45678"
})";
window.location.replace(url);
});
This is return line of my action
return Json(new {OrderNumber = orderNumber, JsonRequestBehavior.AllowGet });
AllowGet should not be part of the object returned, it is the second parameter to Json().
return Json(new { OrderNumber = orderNumber }, JsonRequestBehavior.AllowGet);
Edit: Don't know much about dropzone, but I suspect data is already an object so JSON.parse() might be unnecessary. At any rate, data.OrderNumber or res.OrderNumber should be the order number.
You can't use #Url.Action in javascript because that executes server-side, before the javascript is ever hit. You need to do something like
var url = '/Upload/OrderConfirmation/' + data.OrderNumber;
or if you really need the URL built for you, put in a dummy query string parameter
var url = '#Url.Action("OrderConfirmation", "Upload", new { OrderNumber = XXXXX}"';
and then substitute "XXXXX" with the real order number in the url string.

removing the backslashes in json string using the javascript

i have JSON response which is having backslashes and some responses are not containing the backslashes.
I need to show error message based on the response, How do i parse the JSON response using javascript?
JSON response with out backslashes,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
response with backslashes,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
i tried in the following way but it is working only for JSON response which is not having the backslashes.
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
Actually the problem is not with / slashs. The JSON is INVALID.
remove these " from backend server
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal
Server
Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal
Server Error"}
double quote before "{"timestamp and one after login"}"
these two highlighted and your code will work.
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
You are actually wrapping body object in string at backend which is not valid.
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
var obj = JSON.parse(response)
if(typeof obj._body == "string") {
obj._body = JSON.parse(obj._body)
}
console.log(obj);
Solution:
var response = {"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"};
var body = JSON.parse(response._body);
console.log(body.error);
Explanation:
You have a top level object with one key, _body. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. Unless you are able to fix the server side code, you have to decode the nested JSON manually.

How To Use JSON Returned From a URL in Javascript?

I have a URL which returns JSON data. I would then like to use some parts of this data in Javascript. At the moment I'm getting an 'Uncaught Syntax Error' in the console when I run it.
My code looks like this:
var myAPIcall = "https://maps.googleapis.com/maps/api/geocode/json?address=SW1A1AA&callback=?";
$.get(myAPIcall, function( data ) {
console.log("Place ID = " + data.results.place_id);
}, "json" );
It's the JSON itself which is causing the error.
How can I get the JSON (specifically the place_id, but I'd be happy with any of it) to display with the console.log? If I understand that much I should then be able to move on and use the place_id in my code.
Thanks
Check our query. Removing callback=? will result in a valid JSON :-)
var myAPIcall = "https://maps.googleapis.com/maps/api/geocode/json?address=SW1A1AA";
$.getJSON(myAPIcall, function( data ) {
console.log(data.results[0].place_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Can't display JSON on page

I have been trying to get my JSON code from a PHP file which is connected to my database to display on my website using an XMLHttpRequest, but we cant split them and display it.
We are using an php file example.php that does the following:
function jsonFromQuery($result) {
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json[] = $r;
}
} else {
$json = "Table is empty";
}
return json_encode($json);
}
This will display the json code as following on the website if you open the php file:
[{"UserID":"2","Firstname":"Piet","Lastname":"Klaas","Age":"23","Specialization":"Voet","Branch":"Been","Interests":"Hoofd","Hospital":"OLVG","Email":"pietklaas#gmail.com","ProfilePicture":""}]
With this we use the following javascript file to request this php file and stringify and try and display it.
var request = new XMLHttpRequest;
request.open('GET' , 'http://myurl.nl/example.php', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
var obj = JSON.stringify(request);
var firstname = obj.Firstname;
document.writeln(firstname);`
But I get a massive string which includes the type status etc. And don't know how to split this up to display on their own. For example only Firstname = Piet on the page.
When you get the data back from PHP it's already in the form of a string. You need to use JSON.parse() to convert it into an object you can use. Try...
var obj = JSON.parse(request.responseText);
var firstname = obj[0].Firstname;
document.writeln(firstname);`
Note as well that the Json you're getting back is a list of objects: [{...},{...},{...}], so you can't just call .Firstname as you haven't specified which object you care about. Hence the [0] in the example above to pick out the first object.
One other thought... At present if your PHP doesn't find any results it's going to send back something that isn't in the format you're expecting. Consider either wrapping the list in an object with a status...
{
"Success": true,
"Results": [{...}, {...}]
}
Or make the PHP script return a different HTTP code to indicate failure (404 seems appropriate here)
For future reference, JSON.stringify does the opposite - it takes a complex object and converts it into Json
You are parsing the whole XMLHttpRequest object
var obj = JSON.parse(request);
try using just the response body
var obj = JSON.parse(request.responseText);

Categories

Resources