将json字符串转换为python obj

2024-04-18 15:02:05 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以将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'


Tags: 数据对象字符串idjsonobjurl方式
3条回答

I've tried using simplejson.load() and json.load() but it gave me an error saying 'str' object has no attribute 'read'

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

更有效的方法是,跳过将响应读入字符串的步骤,将响应传递给json.load()

magicJsonData=json.loads(io.StringIO((youMagicData).decode("utf-8"))
print(magicJsonData)

来自任何请求或http服务器的json字符串的类型为byte array 把它们转换成字符串(因为问题是关于从服务器请求返回的字节数组,对吧?)

res = json.loads((response.content).decode("utf-8") )
print(res)

这里的response.content可以是字节数组,也可以是从服务器请求返回的任何字符串,这些字符串被解码为字符串(utf-8)格式并作为python数组返回。

或者只使用bytearray但使用json.load而不是json.loads

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

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函数,因为文件对象只在调用read()时才会放弃数据。因此,由于内置字符串类没有read函数,我们需要一个包装器。简而言之,StringIO.StringIO函数将string类和file类进行子类划分,并对内部工作进行网格划分,这将听到我的低细节重建https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1 所以在这一切结束的时候,就像写一个ram文件,用一行jsoning出来一样。。。。

相关问题 更多 >