Unable to access JSON Element in Javascript via Object.property - javascript

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)

Related

Why it works like this? [duplicate]

I'm parsing some data using a type class in my controller. I'm getting data as follows:
{
"data":{
"userList":[
{
"id":1,
"name":"soni"
}
]
},
"status":200,
"config":{
"method":"POST",
"transformRequest":[
null
],
"transformResponse":[
null
],
"url":"/home/main/module/userlist",
"headers":{
"rt":"ajax",
"Tenant":"Id:null",
"Access-Handler":"Authorization:null",
"Accept":"application/json, text/plain, */*"
}
},
"statusText":"OK"
}
I tried to store the data like this
var userData = _data;
var newData = JSON.parse(userData).data.userList;
How can I extract the user list to a new variable?
The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.
You can test this yourself, e.g. in Chrome's console:
new Object().toString()
// "[object Object]"
JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse("[object Object]")
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.
Try the following instead:
var newData = userData.data.userList;
The first parameter of the JSON.parse function is expected to be a string, and your data is a JavaScript object, so it will coerce it to the string "[object Object]". You should use JSON.stringify before passing the data:
JSON.parse(JSON.stringify(userData))
Don't ever use JSON.parse without wrapping it in try-catch block:
// payload
let userData = null;
try {
// Parse a JSON
userData = JSON.parse(payload);
} catch (e) {
// You can read e for more info
// Let's assume the error is that we already have parsed the payload
// So just return that
userData = payload;
}
// Now userData is the parsed result
Just above JSON.parse, use:
var newData = JSON.stringify(userData)
We can also add checks like this:
function parseData(data) {
if (!data) return {};
if (typeof data === 'object') return data;
if (typeof data === 'string') return JSON.parse(data);
return {};
}
You can simply check the typeof userData & JSON.parse() it only if it's string:
var userData = _data;
var newData;
if (typeof userData === 'object')
newData = userData.data.userList; // dont parse if its object
else if (typeof userData === 'string')
newData = JSON.parse(userData).data.userList; // parse if its string
Unexpected 'O' error is thrown when JSON data or String happens to get parsed.
If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.
I faced similar( although in different context), I solved the following error by removing JSON Producer.
#POST
#Produces({ **MediaType.APPLICATION_JSON**})
public Response login(#QueryParam("agentID") String agentID , Officer aOffcr ) {
return Response.status(200).entity("OK").build();
}
The response contains "OK" string return.
The annotation marked as #Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.
Removing #Produces({ MediaType.APPLICATION_JSON}) works fine.
Output : OK
Beware:
Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'
O is the first letter of the string
JSON.parse(object) compares with jQuery.parseJSON(object);
JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine
The reason for the error is Object is not in the form of string, it is {} and it should be string Object('{}')
Give a try catch like this, this will parse it if its stringified or else will take the default value
let example;
try {
example = JSON.parse(data)
} catch(e) {
example = data
}
First set request value in variable like:
let reqData = req.body.reqData;
if (reqData) {
let reqDataValue = JSON.parse(JSON.stringify(reqData));
}

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

Setting setRequestBody for Rest web services using Post method

Hi I'm trying to create a rest response using post method, I want to dynamically pass the variables instead of hard coding,But where i fail is,when I'm trying to to send an array as a parameter to the Rest web service using post method(example array ["CN=XXX_XX,OU=XXXXX,OU=1_XXXX XXXXity Groups,DC=XXXX,DC=local"]) and I know that there is a better way to do that Please find my code sample.This is the method that gives me a appropriate result.
First Method:(Works)
`
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
var txt = "{\r\n\t\"workflowArgs\":\r\n\t{\r\n\t\"identityName\":\"SiamR\",\r\n\t\"appName\":\"Active Directory\",\r\n\t\"listEntitlements\":[\"CN=ER_CxxxK,OU=xxxxx,OU=1_xxxxxx Security xxx,DC=xxxx,DC=local\"],\r\n\t\"operation\":\"Add\",\r\n\t\"ticketNumber\":\"RITM1234567\"\r\n\t}\r\n}";
r.setRequestBody(txt);
var response = r.execute();
var ResponseBody = response.getBody();
var HTTPCode = response.getStatusCode();
gs.log(ResponseBody);
gs.log(HTTPCode);
} catch (ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"status":"Success"}},"complete":false,"errors":null,"failure":false,"metaData":null,"requestID":"2c988d8c5bd47cf7015bebfb64cf01e6","retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
2n Method (Does not Work):
try {
var r = new sn_ws.RESTMessageV2('SailPoint_IdM', 'post');
r.setStringParameter('"listEntitlements"', '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]');
r.setStringParameter('"identityName"', '"SiarmR"');
r.setStringParameter('"appName"', '"Active Directory"');
r.setStringParameter('"ticketNumber"', '"RITM1234567"');
r.setStringParameter('operation', '"Add"');
//override authentication profile
//authentication type ='basic'/ 'oauth2'
//r.setAuthentication(authentication type, profile name);
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(responseBody );
}
catch(ex) {
var message = ex.getMessage();
}
output:
Script: {"attributes":{"requestResult":{"errors":["An unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo"],"status":"FAIL","GroupStatus":null,"AppStatus":null}},"complete":false,"errors":["Status : failed\nAn unexpected error occurred: sailpoint.tools.GeneralException: The application script threw an exception: java.lang.NullPointerException: Null Pointer in Method Invocation BSF info: script at line: 0 column: columnNo\n"],"failure":false,"metaData":null,"requestID":null,"retry":false,"retryWait":0,"status":null,"success":false,"warnings":null}
Script: 200
Im facing issue with this parameter as im trying to pass this as aray paramenter '["CN=Exxx_xxxK,OU=xxxxion,OU=1_xxxxx Security xxxx,DC=xxx,DC=xxxx"]'
Please suggest a way to implement this and to pass all the variables dynamically if suggesting first method
Below is one of my function, to handle dynamic parameters in either appear in request endpoint (url), headers or body;
For eg: parameter p
var p = {abc: 'def'};
and outbuond rest settings:
rest url = https://xxxx.sss.com/api/showme?name=${abc}
rest headers name = custom-header; value = ${abc}
rest body = {name: "${abc}"}
so it will replace all ${abc} to 'def'
_.isNullOrEmpty - check is obj, string or array is null or empty;
_.loop - loop an obj or array, pass in function(nm/i, val) {}
_.isArray - to check if is array
_.str - convert anything to string
_.rpl - replace all string A to B
restParameters: function (restRequest, obj, endpoint) {
var _ = this;
if ((_.isNullOrEmpty(restRequest)) || (_.isNullOrEmpty(obj))) return;
if (_.isNullOrEmpty(endpoint)) endpoint = restRequest.getEndpoint();
var body = restRequest.getRequestBody();
var headers = restRequest.getRequestHeaders();
_.loop(obj, function(nm, val) {
if (_.isArray(val)) {
val = (_.isNullOrEmpty(val)) ? '[]' : JSON.stringify(val);
} else val = _.str(val);
//for my case my array pass in as string become: "[\"1\", \"2\"]"
//comment below if pass in as object
if (val.contains('"')) val = _.rpl(val, '"', '\\"');
restRequest.setStringParameterNoEscape(nm, val);
var sch = '${' + nm + '}';
endpoint = _.rpl(endpoint, sch, val);
body = _.rpl(body, sch, val);
_.loop(headers, function (hn, hv) {
headers[hn] = _.rpl(hv, sch, val);
});
}, true);
restRequest.setEndpoint(endpoint);
restRequest.setRequestBody(body);
_.loop(headers, function (hn, hv) { restRequest.setRequestHeader(hn, hv); });
}

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

Get json value from response

{"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"}';

Categories

Resources