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
Related
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));
}
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
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)
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));
}
I am coding a block type plugin for Moodle and have this JS code that gives me problems. Since I'm not very familiar with JS and JSON I can't deduce what is the problem.
My code uses this function to add custom action to action link which issues ajax call to php file ...
This is the code:
function block_helpdesk_sendemail(e) {
e.preventDefault();
Y.log('Enetered method');
var sess = {'sesskey=':M.cfg.sesskey};
Y.log(sess);
var ioconfig = {
method: 'GET',
data: {'sesskey=':M.cfg.sesskey},
on: {
success: function (o, response) {
//OK
var data;
try {
data = Y.JSON.parse(response.responseText);
Y.log("RAW JSON DATA: " + data);
} catch (e) {
alert("JSON Parse failed!");
Y.log("JSON Parse failed!");
return;
}
if (data.result) {
alert('Result is OK!');
Y.log('Success');
}
},
failure: function (o, response) {
alert('Not OK!');
Y.log('Failure');
}
}
};
Y.io(M.cfg.wwwroot + '/blocks/helpdesk/sendmail.php', ioconfig);
}
The code pauses in debugger at return line:
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
I've put M.cfg.sesskey and data variables on watch. I can see sesskey data shown, but data variable shows like this:
data: Object
debuginfo: "Error code: missingparam"
error: "A required parameter (sesskey) was missing"
reproductionlink: "http://localhost:8888/moodle/"
stacktrace: "* line 463 of /lib/setuplib.php: moodle_exception thrown
* line 545 of /lib/moodlelib.php: call to print_error()
* line 70 of /lib/sessionlib.php: call to required_param()
* line 7 of /blocks/helpdesk/sendmail.php: call to confirm_sesskey()"
And this is what my logs show:
Enetered method
Object {sesskey=: "J5iSJS7G99"}
RAW JSON DATA: [object Object]
As #Collett89 said, the JSON definition is wrong. His tip might work, but if you need strict JSON data then code the key as string (with quotes):
var sess = {'sesskey': M.cfg.sesskey};
or
var sess = {"sesskey": M.cfg.sesskey};
See definition in Wikipedia
your declaring sesskey in a bizarre way.
try replacing data: {'sesskey=':M.cfg.sesskey},
with data: {sesskey: M.cfg.sesskey},
it might be worth you reading through this
mdn link for javascript objects.
You usually need to JSON.stringify() the objects sent via ajax.
which may be part of the problem.