Skip to content

Instantly share code, notes, and snippets.

@baskan
Last active August 28, 2018 12:35
Show Gist options
  • Save baskan/dc11c7c72a9628afc93a57d95e72a23d to your computer and use it in GitHub Desktop.
Save baskan/dc11c7c72a9628afc93a57d95e72a23d to your computer and use it in GitHub Desktop.
Convert {"@Nill":true} to null on Json responses
/**
* 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