【问题标题】:convert a json string to python object将 json 字符串转换为 python 对象
【发布时间】:2011-04-20 07:55:43
【问题描述】:

是否可以将 json 字符串(例如从 twitter 搜索 json 服务返回的字符串)转换为简单的字符串对象。这是从 json 服务返回的数据的一个小表示:

{
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}

假设我以某种方式将结果存储在某个变量中,例如 obj。我希望获得如下适当的值:

print obj.max_id
print obj.since_id

我尝试过使用simplejson.load()json.load(),但它给了我一个错误提示'str' object has no attribute 'read'

【问题讨论】:

    标签: python json


    【解决方案1】:

    我尝试过使用simplejson.load()json.load(),但它给了我一个错误提示'str' object has no attribute 'read'

    要从字符串加载,请使用json.loads()(注意“s”)。

    更高效,跳过将响应读入字符串的步骤,直接将响应传递给json.load()

    【讨论】:

    • 这不是正确的答案。 json.loads() 创建字典,因此他必须访问像这样的属性 obj['max_id']
    【解决方案2】:

    如果你不知道数据是文件还是字符串......使用

    import StringIO as io
    youMagicData={
    results:[...],
    "max_id":1346534,
    "since_id":0,
    "refresh_url":"?since_id=26202877001&q=twitter",
    .
    .
    .
    }
    
    magicJsonData=json.loads(io.StringIO(str(youMagicData)))#this is where you need to fix
    print magicJsonData
    #viewing fron the center out...
    #youMagicData{}>str()>fileObject>json.loads
    #json.loads(io.StringIO(str(youMagicData))) works really fast in my program and it would work here so stop wasting both our reputation here and stop down voting because you have to read this twice 
    

    来自https://docs.python.org/3/library/io.html#text-i-o

    json.loads 来自 python 内置库,json.loads 需要一个文件对象并且不检查它传递的内容,因此它仍然会根据您传递的内容调用 read 函数,因为文件对象仅在您调用时放弃数据读()。所以因为内置的字符串类没有读取函数,我们需要一个包装器。所以简而言之,StringIO.StringIO 函数将字符串类和文件类子类化,并对内部工作进行网格化,从而听到我的低细节重建https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1 所以最后这就像写一个 ram 文件并将它放在一行中....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 2020-05-27
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      相关资源
      最近更新 更多