7

Python 3.3.2 import json & urllib.request

Json

[{"link":"www.google.com","orderid":"100000222"},
{"link":"www.google.com","orderid":"100000222"},
{"link":"www.google.com","orderid":"100000222"}]

print(response.info())

Date: Sun, 20 Oct 2013 07:06:51 GMT
Server: Apache
X-Powered-By: PHP/5.4.12
Content-Length: 145
Connection: close
Content-Type: application/json

Codes

url = "http://www.Link.com"
    request = urllib.request.Request(url)
    request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
    request.add_header('Content-Type','application/json')
    response = urllib.request.urlopen(request)

    decodedRes = response.read().decode('utf-8')
    json_object = json.load(decodedRes)

The following are my codes Error

Traceback (most recent call last):
  File "C:\Users\Jonathan\Desktop\python.py", line 57, in <module>
    checkLink()
  File "C:\Users\Jonathan\Desktop\python.py", line 50, in checkLink
    json_object = json.load(decodedRes)
  File "C:\Python33\lib\json\__init__.py", line 271, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> .

Any idea how i can fix this issue?

JohnK
  • 6,865
  • 8
  • 49
  • 75
CodeGuru
  • 3,645
  • 14
  • 55
  • 99

4 Answers4

21

Use json.loads instead of json.load.

json.loads(decodedRes)

>>> import json
>>> json.load('{"a": 1}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 286, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> json.loads('{"a": 1}')
{u'a': 1}

Alternatively you can pass response object to json.load:

## decodedRes = response.read().decode('utf-8')
json_object = json.load(response)
falsetru
  • 357,413
  • 63
  • 732
  • 636
4

Try replacing the json.load() with json.loads() . The former needs a file-stream thats the reason you are running into the attribute error.

feverDream
  • 283
  • 2
  • 16
4

Following code loads json file into document. Document will have values of dict type.

file_name = "my_file.json"
with open(file_name, 'r') as f:
    document =  json.loads(f.read())
Manikandan
  • 690
  • 5
  • 5
0

It's very simple, You just need to import beautiful soup in another way. Right now you are importing as

from beautifulSoup import BeautifulSoup

Change it to

from bs4 import BeautifulSoup
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Patel Sunil
  • 441
  • 7
  • 7