0

Is there a way to tell if a feed is XML, JSON, or both?

CoffeeRain
  • 4,460
  • 4
  • 31
  • 50
bresson
  • 831
  • 11
  • 20
  • Just a note: a feed can't simultaneously be both valid XML and valid JSON. It would require a custom reader to extract the information for each of the formats from a single document, and if it requires custom reading logic, it's not valid for the format in question. – jlbang Jul 27 '19 at 00:25

2 Answers2

3

The best and sure-fire way would be simply to run it through a XML and a JSON parser, and see which one works without generating syntax errors. For example, in PHP, try json_encode($feed_string) and $xml = new SimpleXMLElement($feed_string);

Alternatively, you can just do some simple string checking. All properly-formed XML documents start with <?xml, while JSON typically starts with { since the feed data is a Javascript object.

The samples Google provides as the two feed formats may be helpful:

http://code.google.com/apis/gdata/docs/json.html

phsource
  • 2,326
  • 21
  • 32
  • Although it's a good idea to include it, the XML declaration is not guaranteed to be present in a well-formed XML file. See http://www.w3.org/TR/REC-xml/#sec-prolog-dtd and note that an XML declaration is SHOULD instead of MUST. – MNGwinn Jul 09 '12 at 14:51
  • Also, proper JSON can start with an array `[ ... ]` as well as an object `{ ... }` – Joseph May 20 '18 at 02:11
2

I'm not really clear on what you mean by 'feed', but if the mime type of a file is set to application/json, then it is JSON. XML has two standard mime types (application/xml and text/xml).

If you don't have access to the mime types (or they are ambiguous), you can check for <?xml at the start of a proper xml file. And if that isn't there, then you can probably do a pretty good guess that it is XML if it starts with just < and JSON if it starts with {. But there is no guarantee they will be correctly formed.

RodeoClown
  • 13,338
  • 13
  • 52
  • 56
  • sorry rodeoclown but i forgot to add RSS feed in the body. my impressions were XML and JSON were the two main standards for delivering RSS – bresson Jun 03 '10 at 02:11
  • 1
    No worries. RSS is XML by definition. See http://stackoverflow.com/questions/246577/can-i-serve-rss-in-json for some other people who have used JSON to create an RSS-like feed. – RodeoClown Jun 03 '10 at 02:15