您得到的字符串不是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']
這是一個字符串?你能告訴我們你正在嘗試什麼嗎? – mgilson
我有一個來自URL的文本文件,我需要解析此文件以從文件中提取特定的字段:) – ammoun
@ammoun你在那裏有一個python對象,而不是一個json字符串。我期望文本文件將是一個字符串,所以'json.loads'應該可以工作。 – quamrana