12

I am trying to read a json file from python script using the json module. After some googling I found the following code:

with open(json_folder+json) as json_file:
        json_data = json.loads(json_file)
        print(json_data)

Where json_folder+json are the path and the name of the json file. I am getting the following error:

str object has no attribute loads. 
1
  • If json is a string with a filename, what do you want to achieve by calling loads on the string? Commented Oct 3, 2014 at 11:36

5 Answers 5

18

The code is using json as a variable name. It will shadow the module reference you imported. Use different name for the variable.

Beside that, the code is passing file object, while json.loads accept a string.

Pass a file content:

json_data = json.loads(json_file.read())

or use json.load which accepts file-like object.

json_data = json.load(json_file)
Sign up to request clarification or add additional context in comments.

Comments

10
import json
f = open( "fileToOpen.json" , "rb" )
jsonObject = json.load(f)
f.close()

it should seems you are doing in rather complicated way.

Comments

3

Considering the path to your json file is set to the variable json_file:

import json

with open(json_file, "rb") as f:
    json_data = json.load(f)

print json_data

Comments

1

Try like this :-

json_data=open(json_file)
data = json.load(json_data)
json_data.close()

Comments

-1

I Make This....

import urllib2

link_json = "\\link-were\\"
link_open = urllib2.urlopen(link_json) ## Open and Return page.
link_read = link_open.read()           ## Read contains of page.

json = eval(link_read)[0]              ## Transform the string of read in link_read and return the primary dictionary ex: [{dict} <- return this] <- remove this

print(json['helloKey'])

Hello World

1 Comment

Not sure how this is relevant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.