简体   繁体   中英

readingJSON with simplejson python

i'm trying to read JSON after i'm sending url request with urllib2.

my code:

request = urllib2.Request("https://127.0.0.1:443/myAPI", data=form_data, headers=headers)
response = urllib2.open(request) 

So the problem is when i'm trying to read to JSON from the respond object. i'm doing it like that

 simplejson.loads(response.read())

the error i get is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/new/main3/python/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/opt/new/main3/python/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/opt/new/main3/python/simplejson/decoder.py", line 420, in raw_decode
    raise JSONDecodeError("No JSON object could be decoded", s, idx)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

The interesting part is when i'm sending the request in my firefox browser, I'm typing the address 127.0.0.1/myAPI at the url line , i do get the json on screen and i can see it at the debug mode as a JSON {"hosts": [{"host": "127.0.0.1:4448"}]}

so the json is valid..

at the debug i'm getting this page:

    <!DOCTYPE html>
<html>
<head>
    <!-- framebusting -->
    <style>
        html{display : none ;}
    </style>
    <script type="text/javascript">
        if (self == top) {
            document.documentElement.style.display = "block";
        } else {
            top.location = self.location;
        }
    </script>
    <script type="text/javascript" src="js/detectBrowser.js"></script>
    <meta charset="utf-8"/>
    <link rel="StyleSheet" href="css/forensics.css" type="text/css" media="screen"/>
</head>
<body>
    <script type="text/javascript" src="libs/requirejs/require.js" data-main="js/login.js"></script>
</body>
</html>

is any one have some way to solve it , or how can i read the json text straight from the respond object , or even look at that at the debug

I appreciate ant help , i'm trying for the least 3 days to figure it out Thanks

I think it's because of this simplejson.loads(response .read()) . You have a space between response and .read()

Try the following:

request = urllib2.Request("https://127.0.0.1:443/myAPI", data=form_data, headers=headers)
response = urllib2.open(request) 
response_body = response.read()
response_body_json = simplejson.loads(response_body)

so it was my bad and the api was need a coockie. after adding a cookie header i was receiving a correct JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM