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'

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

所以,在反序列化之前,如何确保它也有一个引用?

This is the error I get -

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

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模块.

Json相关问答推荐

Vega Lite中的图例对齐

如何在我的响应模型中修复此问题:[期望的值类型为';Map<;Dynamic,Dynamic&>;,但获得的值类型为';NULL&39;]

使用json_query更新事实

解析SQL中的嵌套JSON

使用 map_values Select 包含空格的字符串未按预期工作

打印与 JSON 和 PowerShell 中的模式匹配的子项的父项名称

如何使用 serde_json 构建有状态的流式解析器?

在 CodePipeline 中调用 lambda 时传递用户参数

将请求中的数据推送到数组中

父键中的 Perl JSON 数组

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

了解 JSON Schema 草稿版本 4 中的additionalProperties关键字

在 Http Header 中使用 Json 字符串

使用 gson 反序列化对象的特定 JSON 字段

Java循环遍历Json数组?

春天:返回@ResponseBodyResponseEntity>

JSON 和 BSON 哪个更轻量级?

Newtonsoft 对象 → 获取 JSON 字符串

仅使用字符串和值解析 JSON 对象

使用 jQuery 和 JSON 填充表单?