Last active
August 28, 2018 12:35
-
-
Save baskan/dc11c7c72a9628afc93a57d95e72a23d to your computer and use it in GitHub Desktop.
Convert {"@Nill":true} to null on Json responses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* It's pretty annoying that some .net applications cast null as { "@nill" : true } | |
* This could cause your application that expecting some string or integers but instead | |
* receiving that annoying @nill object. To remove this we have to transform the API response | |
* to remove those ugly objects to JS safe null's. | |
* | |
* @author Ilkin Baskan [email protected] - github.com/baskan | |
*/ | |
// a handy object/array detection you might find this useful too. | |
export const isArr = (data) => Object.prototype.toString.call(data) == '[object Array]'; | |
export default function ConvertNillAnnotationsToNullOnApiResponse (responseData) { | |
let obj = {...responseData}; | |
const keys = Object.keys(obj); | |
// the evil: | |
if (keys.length == 1 && obj.hasOwnProperty("@nil") && obj["@nil"]) { | |
return null; | |
} | |
const recurseifNecessary = (val) => { | |
if (val && typeof val === 'object') { | |
if (isArr(val)) { | |
return val.map(v => recurseifNecessary(v)) | |
} | |
return ConvertNillAnnotationsToNullOnApiResponse(val); // recurse calling. | |
} | |
return val | |
} | |
keys.forEach(key => { | |
obj[key] = recurseifNecessary(obj[key]); | |
}); | |
return obj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment