I get data json throw ajax from action-struts 2 for my view. some data set of data.
Example
{"home":"1234","room": null}.
I can read data.home
, and I get 1234 value, but when I try read data.room
, I got Uncaught error in console of browser, How can I do to manage this Uncaught error...
JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
What went wrong? JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.
To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.
JSON values cannot be one of the following data types: a function. a date. undefined.
just add a test
/* ------
var
data = {"home":"1234","room": null},
h = (data.home) ? data.home : '',
r = (data.room) ? data.room : 0;
------ */
var
data = {"home":"1234","room": null},
h = data.home || '',
r = data.room || 0;
console.log('h=',h);
console.log('r=',r);
In this way you can deal with null values in your object ,you can replace them with empty string or whatever values you want you wont face exception in this way in browser.See JSON.parse
let obj={"home":"1234","room": null};
let newobj=JSON.parse(JSON.stringify(obj),(key,value)=> value===null? "" : value )
console.log(newobj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With