2013-05-20 35 views
0

我在另一個問題中詢問了此對象的類型,它是來自URL的文本文件。無法將JSON文件加載到python中

variable = [["1","arbitrary string","another arbitrary string"], 
["2","arbitrary string","another arbitrary string"], 
["3","arbitrary string","another arbitrary string"], 
["4","arbitrary string","another arbitrary string"]]; 
another_variable = "arbitrary string"; 

有人告訴我,這是一個JSON對象,但是當我嘗試json.loads,我得到一個錯誤說「不JSON對象可以解碼」

我在想什麼吧。

+1

這是一個字符串?你能告訴我們你正在嘗試什麼嗎? – mgilson

+0

我有一個來自URL的文本文件,我需要解析此文件以從文件中提取特定的字段:) – ammoun

+0

@ammoun你在那裏有一個python對象,而不是一個json字符串。我期望文本文件將是一個字符串,所以'json.loads'應該可以工作。 – quamrana

回答

0

Daniel Roseman是正確的。這不是JSON字符串。只要確保在列表的每個元素之間包含逗號(您留下了一個)。

variable = [["1","arbitrary string","another arbitrary string"],["2","arbitrary string","another arbitrary string"],["3","arbitrary string","another arbitrary string"],["4","arbitrary string","another arbitrary string"]] 

variable 
[[u'1', u'arbitrary string', u'another arbitrary string'], 
[u'2', u'arbitrary string', u'another arbitrary string'], 
[u'3', u'arbitrary string', u'another arbitrary string'], 
[u'4', u'arbitrary string', u'another arbitrary string']] 

another_variable = "arbitrary string" 

another_variable 
u'arbitrary string' 
+0

仍然沒有運氣... – ammoun

+0

注意,你在第一次分配缺少一個逗號: ] [ 「3」, 應該已經 ],[ 「3」 –

0

json.loads在字符串上工作。它將JSON編碼的字符串解碼爲一個Python對象。您在這裏得到的是一個Python對象,您可以使用json.dumps編碼爲JSON。另外,JSON中沒有可變賦值。你唯一可以代表的是一個普通的對象。

+0

試過了,沒有運氣。 – ammoun

+0

@ammoun你試過這樣的事情? 變量= [[「1」,「任意字符串」,「另一個任意字符串」], [「2」,「任意字符串」,「另一個任意字符串」], [「3」 ,「另一個任意字符串」], [「4」,「任意字符串」,「另一個任意字符串」]]; another_variable =「任意字符串」; print(json.dumps(variable)) print(json.dumps(another_variable)) – sagittarian

+0

事實上,我複製的文本來自一個URL,所以我不能將它粘貼到我的代碼中,除非你知道另一種方法。 – ammoun

0

您得到的字符串不是JSON(如前所述),但部分可以解釋爲JSON(= statement的右部分)。你可以嘗試編寫簡單的解析器來提取對你有意義的東西。我周圍玩,並得到這個:

import json 
json_str = """ 
variable = [["1","arbitrary string","another arbitrary string"], 
["2","arbitrary string","another arbitrary string"], 
["3","arbitrary string","another arbitrary string"], 
["4","arbitrary string","another arbitrary string"]]; 
another_variable = "arbitrary string"; 
""" 

json_str_list = [js.strip().split("=")[1] for js in json_str.split(";") if js.strip()] 
print("=preprocessed: %r" % json_str_list) 
print("=json decoded: %r" % [json.loads(js) for js in json_str_list]) 

輸出爲:

=preprocessed: [' [["1","arbitrary string","another arbitrary string"],\n["2","arbitrary string","another arbitrary string"],\n["3","arbitrary string","another arbitrary string"],\n["4","arbitrary string","another arbitrary string"]]', ' "arbitrary string"'] 

=json decoded: 
[ 
[[u'1', u'arbitrary string', u'another arbitrary string'], 
[u'2', u'arbitrary string', u'another arbitrary string'], 
[u'3', u'arbitrary string', u'another arbitrary string'], 
[u'4', u'arbitrary string', u'another arbitrary string']], 

u'arbitrary string']