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,

Recommended Answers

All 4 Replies

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

can you be more descriptive please

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.