2010-10-02 65 views
29

是否可以将json字符串(例如从twitter搜索json服务返回的字符串)转换为简单的字符串对象。下面是从JSON服务返回的数据的小图示:将json字符串转换为python对象

{ 
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()尝试,但它给了我使用simplejson.load()json.load(),但一个错误说'str' object has no attribute 'read'

回答

65

我试着给了我一个错误说'str' object has no attribute 'read'

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

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

+0

哦,不知道,我得到一本字典。无论如何,这是罚款的时刻... – deostroll 2010-10-02 20:53:49

0

,如果你不知道的数据将是一个文件或字符串....使用

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()时只会放弃数据。所以,因为内置的字符串类没有读取功能,我们需要一个包装。所以,StringIO.StringIO函数简而言之,就是将字符串类和文件类分开,并将内部工作网格化,从而获得我的低细节重建https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1 ,因此最终完成了它的任务,就像编写一个ram文件并将其一行一行地截取出来一样。 ...

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

任何请求或HTTP服务器的JSON字符串的类型为字节数组 的将它们转换到字符串,(因为问题是关于字节数组从服务器请求返回的,对吧?)

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

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

或者只是使用一个字节组,但使用json.load代替json.loads