Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json value in Null hot to catch Javascript exception

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...

like image 894
Erikson Rodriguez Avatar asked May 23 '19 01:05

Erikson Rodriguez


People also ask

Can JSON take null values?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

Does JSON parse throw error?

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.

How do I check if a string is JSON Parsable?

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.

Does JSON allow undefined values?

JSON values cannot be one of the following data types: a function. a date. undefined.


2 Answers

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);
like image 126
Mister Jojo Avatar answered Nov 10 '22 12:11

Mister Jojo


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)
like image 42
Shubh Avatar answered Nov 10 '22 14:11

Shubh