0

我有一个包含至少 30 000 个字典的 json 文件。在这里能找到它:

http://openxcplatform.com.s3.amazonaws.com/traces/nyc/downtown-west.json

我浏览了互联网,发现这让我最接近我需要的东西,因为我需要一个一个地阅读 json 文件,将 dicts 作为实际 dict 输入到列表中:

with open("test.json") as data_file:
    for x in data_file:
        json.dumps(it.append(ast.literal_eval(x)))

我测试了这段代码,它在大多数情况下都有效。我测试了前 2000 个元素,但是,一旦我测试了整个文件,我就会收到这个错误:

  File "converter.py", line 58, in <module>
    if __name__ == "__main__": main()
  File "converter.py", line 34, in main
    json.dumps(it.append(ast.literal_eval(x)))
  File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python2.7/ast.py", line 63, in _convert
    in zip(node.keys, node.values))
  File "/usr/lib/python2.7/ast.py", line 62, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "/usr/lib/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

任何人都知道为什么会发生这种情况?

4

3 回答 3

2

首先,该文件不是 JSON 格式,而是JSON-lines

其次,您不想使用 读取 JSON 数据ast.literal_eval,因为它 1) 非常不安全,2) 不是 JSON 解析器并在看到false或时抛出错误true

使用json.loads

于 2016-02-25T22:59:45.580 回答
1

您不想使用json.dumps它将字典转换为 JSON。您正在做相反的事情 - 读取 JSON 并转换为 dict。您需要为此使用json.loads()

it = []
failures = []

with open('you_file.json') as f:
  for line in f:
    try:
      it.append(json.loads(line))
    except Exception:
      failures.append(line)

print 'Parsed {0} lines'.format(len(it))
print 'Failed {0} lines'.format(len(failures))
于 2016-02-25T22:45:37.963 回答
0

我发现在 Google App Engine 的 Python 中使用 TypeError: expected string or buffer有助于让程序正常运行。仅使用 json.loads 给了我一个类型错误。

于 2016-02-29T14:55:39.473 回答