无法将JSON文件加载到python中

时间:2013-05-20 19:55:57

标签: python json object format

我在另一个问题中询问了这个对象的类型,它是一个来自URL的文本文件。

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对象可以被解码”

我想要的是什么。

3 个答案:

答案 0 :(得分:0)

json.loads适用于字符串。它将JSON编码的字符串解码为Python对象。你在这里有一个Python对象,你可以使用json.dumps将其编码为JSON。此外,JSON中没有变量赋值。你唯一可以代表的是一个普通的对象。

答案 1 :(得分:0)

丹尼尔罗斯曼是对的。这不是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'

答案 2 :(得分: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']