繁体   English   中英

从python读取json文件

[英]Read json file from python

我正在尝试使用json模块从 python 脚本读取 json 文件。 经过一番谷歌搜索后,我发现了以下代码:

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

其中json_folder+json是 json 文件的路径和名称。 我收到以下错误:

str object has no attribute loads. 

代码使用json作为变量名。 它将隐藏您导入的模块引用。 为变量使用不同的名称。

除此之外,代码传递文件对象,而json.loads接受一个字符串。

传递一个文件内容:

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

或使用接受类文件对象的json.load

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

看起来你正在以相当复杂的方式做。

像这样尝试:-

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

考虑到 json 文件的路径设置为变量json_file

import json

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

print json_data

我做这个....

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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