简体   繁体   中英

Read json file from python

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. 

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)
import json
f = open( "fileToOpen.json" , "rb" )
jsonObject = json.load(f)
f.close()

it should seems you are doing in rather complicated way.

Try like this :-

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

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

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

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