Reading json file from python

I am trying to read a json file from a python script using the json library. 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 is json_folder + json path and json file name. I get the following str error object that has no attributes.

+6
source share
5 answers

The code uses json as the name of the variable. It obscures the link to the module you imported. Use a different name for the variable.

In addition, the code passes the file object, and json.loads takes the string.

Transfer the contents of the file:

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

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

 json_data = json.load(json_file) 
+7
source
 import json f = open( "fileToOpen.json" , "rb" ) jsonObject = json.load(f) f.close() 

It seems that you are doing in a rather complicated way.

+2
source

Try the following: -

 json_data=open(json_file) data = json.load(json_data) json_data.close() 
+1
source

Given that the path to your json file is set to the json_file variable:

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

I'm doing it....

 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
source

Source: https://habr.com/ru/post/976206/


All Articles