0

我在另一个问题中询问了这个对象的类型,它是一个来自 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 对象”

请问我错过了什么。

4

3 回答 3

0

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

于 2013-05-20T20:05:34.883 回答
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'
于 2013-05-20T20:08:10.863 回答
0

您得到的字符串不是 JSON(如前所述),但部分可以解释为 JSON(= 语句的右侧部分)。您可以尝试编写简单的解析器来提取您感兴趣的内容。我玩过并得到了这个:

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']
于 2013-05-20T22:02:59.860 回答