簡體   English   中英

將json字符串轉換為python對象

[英]convert a json string to python object

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

我已經嘗試過使用simplejson.load()json.load()但是它給了我一個錯誤,說'str' object has no attribute 'read'

要從字符串加載,請使用json.loads() (注意's')。

更有效率,跳過將響應讀入字符串的步驟,並將響應傳遞給json.load()

如果您不知道數據是文件還是字符串....使用

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-io

json.loads來自python內置庫,json.loads需要一個文件對象並且不檢查它傳遞的是什么,所以它仍然會調用你傳遞的函數的read函數,因為文件對象只在你調用read()時放棄了數據。 因為內置的字符串類沒有read函數,我們需要一個包裝器。 所以StringIO.StringIO函數簡而言之,子類化字符串類和文件類,並將內部工作網格化,聽到我的低細節重建https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1所以最后它就像寫作一樣一個ram文件並將其排成一行....

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數組返回。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM