Hello All,
Ii want to know how can i check whether the response from the server is inJSON format or XML format .
Please let me know how to do this,

Hello All,
Ii want to know how can i check whether the response from the server is inJSON format or XML format .
Please let me know how to do this,

The first idea is try and parse it with json.loads(), if it raises ValueError, it may well be xml

>>> import json
>>> json.loads('<?xml version="1.0" encoding="UTF-8" ?>')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.6/json/decoder.py", line 338, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Edited 5 Years Ago by Gribouillis: n/a

can you be more descriptive please

Well, I mean that you could handle the server's answer like this

import json

def handle_server_answer(the_answer):
    try:
        json_data = json.loads(the_answer)
    except ValueError:
        # the answer was not in json
        other_handler(the_answer)
        return
    # do something with the json data
    print("The server sent json data %s" % repr(json_data))

def other_handler(the_answer):
    # may be try to parse with an xml parser like lxml
    pass

Edited 5 Years Ago by Gribouillis: n/a

XML data stream starts with an opening tag '<'
more elaborately '<?xml'

Edited 5 Years Ago by sneekula: n/a

This article has been dead for over six months. Start a new discussion instead.