3

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

user2727195
  • 7,122
  • 17
  • 70
  • 118

4 Answers4

3

You can use RegExp /application\/json/

var response = {"Content-Type":"application/json;charset=UTF-8"};
console.log(response["Content-Type"].match(/application\/json/)[0]);
guest271314
  • 1
  • 15
  • 104
  • 177
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
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

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])
spacether
  • 2,136
  • 1
  • 21
  • 28
0

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.

Community
  • 1
  • 1
Jezor
  • 3,253
  • 2
  • 19
  • 43
  • A better refactoring would be `^(application\/(json|x-javascript)|text\/(x-)?javascript|x-json)(;.*)?$`. The slashes don't need to be escaped for the regex to be correct, but if your language uses slashes as regex separators, you do need the backslashes for that reason. – tripleee Jun 30 '16 at 07:56