python json解析 超过对象_使用Python解析JSON时,“模块”对象没有属性“加载”...

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

import json

File "/cygdrive/c/ZookPython/json.py", line 4, in

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

AttributeError: 'module' object has no attribute 'loads'

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

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

Update:-

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?

This is the error I get -

Traceback (most recent call last):

File "jsontest.py", line 7, in

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

import json

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值