This particular application is returning content-type
headers in the format application/json;charset=UTF-8
I'm not sure if this could change and get reduced to 'application/json' only or may be if I reuse this code somewhere else for?
My code is
response.headers['Content-Type'].match(/text\/application//json/i)
How to best check for content type application/json???
This particular application is returning content-type
headers in the format application/json;charset=UTF-8
I'm not sure if this could change and get reduced to 'application/json' only or may be if I reuse this code somewhere else for?
My code is
response.headers['Content-Type'].match(/text\/application//json/i)
How to best check for content type application/json???
Share Improve this question asked Jun 25, 2016 at 22:51 user2727195user2727195 7,34020 gold badges73 silver badges121 bronze badges4 Answers
Reset to default 3You can use RegExp
/application\/json/
var response = {"Content-Type":"application/json;charset=UTF-8"};
console.log(response["Content-Type"].match(/application\/json/)[0]);
There are many json content types that don't begin with application/json.
See 24 of them here.
One example is application/geo+json
The regex /application\/[^+]*[+]?(json);?.*/
captures all of those and the vanilla application/json
with or without charset information.
It works for:
application/json
application/json; charset=UTF-8
application/json-patch+json
application/geo+json
Per:
console.log("application/json".match(/application\/[^+]*[+]?(json);?.*/)[1])
console.log("application/json; charset=UTF-8".match(/application\/[^+]*[+]?(json);?.*/)[1])
console.log("application/json-patch+json".match(/application\/[^+]*[+]?(json);?.*/)[1])
console.log("application/geo+json".match(/application\/[^+]*[+]?(json);?.*/)[1])
I think you are doing right, You can check this using regex . If it returns null then it means it is not json.
if (response.headers['Content-Type'].match(/application\/json/i)){
// do your stuff here
}
Other way is to find application/json
string in header string
if (response.headers['Content-Type'].contains('application/json')){
// do your stuff here
}
There are multiple JSON
content-types. Not all of them are "official", but if you are trying to match them all, try this regex:
^((application\/json)|(application\/x-javascript)|(text\/javascript)|(text\/x-javascript)|(text\/x-json))(;+.*)*$
You can add / delete content types from the regex, just remember to put proper parenthesis around them.