Get json value from response - javascript

{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
If I alert the response data I see the above, how do I access the id value?
My controller returns like this:
return Json(
new {
id = indicationBase.ID
}
);
In my ajax success I have this:
success: function(data) {
var id = data.id.toString();
}
It says data.id is undefined.

If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301

Normally you could access it by its property name:
var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);
or perhaps you've got a JSON string that needs to be turned into an object:
var foo = jQuery.parseJSON(data);
alert(foo.id);
http://api.jquery.com/jQuery.parseJSON/

Use safely-turning-a-json-string-into-an-object
var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
var jsonObject = (new Function("return " + jsonString))();
alert(jsonObject.id);

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results is now an object.

If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

Related

forEach is not a function even with JSON.parse

I am having trouble with looping JSON data. I always get the error data.forEach is not a function even do i use JSON.parse. Anyone know how to fix this problem ?
function getApiGebruiker() {
CallWebAPI();
//nieuw deel
var url = "http://localhost:8081/persoons";
//do get request
var client = new HttpClient();
client.get("http://myIPadress/persoons", function (response) {
// do something with response
var data = JSON.parse(response);
console.log(data);
//data = JSON.parse(data);
let string = document.getElementById("pwd").value;
let loginn = document.getElementById("login").value;
data.forEach((persoons) => {
console.log(persoons.gebruikersnaam);
});
});
Your data seems to be an object ({}) and not an array ([]).
Try:
var data = JSON.parse(response);
var people = data._embedded.persoons
people.forEach((persoon) => {
console.log(persoon.gebruikersnaam);
});

Can't get the value of json object

I have this json object, and i want to get the value of the error but it always returning me an undefined result.
Here is the json object
{"isValid":false,"errors":["Username is required.","Password is required."]}
my code is:
success: function (response) {
var JSONstring = JSON.stringify(response);
var JSONobject = JSON.parse(JSONstring);
alert(JSONstring);
alert(JSONobject);
console.log(JSONobject);
var _result = JSONobject.errors;
i have also tried:
var _result = JSONobject[0]['errors'];
var _result = JSONobject['errors'][0];
but still i can't access the value.
If you already have access to the JSON object you can work with it without manipulation. If your question was also looking to get it in that form, see this StackOverflow answer for how to format your request.
success: function (response) {
// Assuming response = {"isValid":false,"errors":["Username is required.","Password is required."]}
// Directly access the property errors
var errors = response.errors;
console.log(errors); // ["Username is required.","Password is required."]
JSFiddle

Unable to access JSON Element in Javascript via Object.property

I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)

How to extract the response from ajax call using js?

I have a ajax call on my function
js part
_this.ajaxPost(appUrl + "reports/appointment/save", post_str, function(response) {
var res = eval("(" + response + ")");
if (!res.error) {
var data = res.msg;
} else {
if (res.status == "error") {
_this.showPopMsg("error", 'Error when updating db ', res.msg);
}
}
}, function(response) {
alert(response);
var res = eval("(" + response + ")");
_this.showPopMsg("error", 'Updating DB', res.msg);
});
php part
echo json_encode(array("error"=> false, "status"=>"success", "msg"=>$conditions['reg']->result()));
which returns a response like,
{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}
and I'm trying to extract the msg part using js, the msg part contains an array like
[{"name":"dream hunter","mob_num":"9876543210","email":"afl#thnfgd"}]
and here name,mob-num and email are keys and I'm trying to extract their values
I have tried
var res = eval("(" + response + ")");
var data = res.msg;
alert(data[name]);//which is the first key
which is not working. How can I extract this?
Assuming you have the following response:
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}'
Using JSON.Parse you can extract the object:
var y = JSON.parse(x);
Now you have an object like this:
{
error:false,
msg: [{
email: "afl#thnfgd"
mob_num: "9876543210"
name: "dreamhunter"
}],
status:"success"
}
To access the properties, such as the email for example, of the first message you can do this:
console.log(y.msg[0].email);
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}'
var y = JSON.parse(x);
console.log('msg[0].email: ', y.msg[0].email);
You can view the data using :-
alert(data[0].name);
Use the JSON object methods to handle JSON in javascript.
For instance
var data = JSON.parse('{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}')
alert(data.msg[0].name)

JSON anonymous type property undefined?

in my mvc3 roject, I return the Json object:
return Json(new { ID = guid, FileName = file.FileName, FullPath = filename });
then, in the JS code, I try to acces to the fields, e.g:
onComplete: function (event, queueId, fileObj, response, data) {
alert(response.ID); //test
}
but i get the undefined message. If i just get the alert(response); I see the valid object:
{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}
so how to access to that properties ?
You're probably seeing the JSON text that needs to be parsed into JavaScript data structures.
var parsed = JSON.parse(response);
alert( parsed.ID );
Without parsing it, you're trying to access the ID property of a String object.
var str = '{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}';
alert( str.ID ); // undefined

Categories

Resources