'module' 对象在使用 python 解析 JSON 时没有属性 'loads' [英] 'module' object has no attribute 'loads' while parsing JSON using python

查看:58
本文介绍了'module' 对象在使用 python 解析 JSON 时没有属性 'loads'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Python 解析 JSON.我最近开始使用 Python,所以我学习了一些如何使用 Python 解析 JSON 的 stackoverflow 教程,然后我想出了以下代码 -

I am trying to parse JSON from Python. I recently started working with Python so I followed some stackoverflow tutorial how to parse JSON using Python and I came up with below code -

#!/usr/bin/python
import json

j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
print j['script']

但是每当我运行上面的代码时,总是出现这个错误 -

But whenever I run the above code, I always get this error -

Traceback (most recent call last):
  File "json.py", line 2, in <module>
    import json
  File "/cygdrive/c/ZookPython/json.py", line 4, in <module>
    j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
AttributeError: 'module' object has no attribute 'loads'

有没有想过我在这里做错了什么?我在 Windows 中运行 cygwin,从那里我只运行我的 python 程序.我使用的是 Python 2.7.3

Any thoughts what wrong I am doing here? I am running cygwin in windows and from there only I am running my python program. I am using Python 2.7.3

还有什么更好更有效的方式来解析 JSON 吗?

And is there any better and efficient way of parsing the JSON as well?

更新:-

如果我删除单引号,下面的代码将不起作用,因为我是从其他方法获取 JSON 字符串的 -

Below code doesn't work if I remove the single quote since I am getting JSON string from some other method -

#!/usr/bin/python

import json

jsonStr = {"script":"#!/bin/bash echo Hello World"}

j = json.loads(jsonStr)
shell_script = j['script']
print shell_script

那么在反序列化之前如何确定,它也有单引号?

So before deserializing how to make sure, it has single quote as well?

这是我得到的错误 -

Traceback (most recent call last):
  File "jsontest.py", line 7, in <module>
    j = json.loads(jsonStr)
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

推荐答案

File "json.py", line 2, in <module>
  import json

这一行是一个赠品:您已将脚本命名为json",但您正在尝试导入名为json"的内置模块,因为您的脚本位于当前目录中,因此它首先出现在 sys.path 中,并且所以这就是导入的模块.

This line is a giveaway: you have named your script "json", but you are trying to import the builtin module called "json", since your script is in the current directory, it comes first in sys.path, and so that's the module that gets imported.

您需要将脚本重命名为其他名称,最好不是标准的 Python 模块.

You need to rename your script to something else, preferrably not a standard python module.

这篇关于'module' 对象在使用 python 解析 JSON 时没有属性 'loads'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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