从python读取json文件 [英] Read json file from python

查看:918
本文介绍了从python读取json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to read json file from 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)

其中json_folder + json json文件的路径和名称.我收到以下错误str对象没有属性加载.

Where json_folder+json the path and name of json file. I am getting the following error str object has no attribute loads.

推荐答案

代码使用json作为变量名.它将隐藏您导入的模块引用.为变量使用其他名称.

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

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

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

传递文件内容:

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

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

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

json_data = json.load(json_file)

这篇关于从python读取json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆