【问题标题】:Error in reading from json file with multiple dicts从具有多个 dicts 的 json 文件中读取错误
【发布时间】:2016-02-25 22:34:17
【问题描述】:

我有一个包含至少 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

有人知道为什么会这样吗?

【问题讨论】:

    标签: python json string dictionary malformed


    【解决方案1】:

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

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

    使用json.loads

    【讨论】:

      【解决方案2】:

      您不想使用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))
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2015-06-08
          • 2018-01-11
          • 1970-01-01
          • 1970-01-01
          • 2019-05-14
          • 2020-05-21
          • 1970-01-01
          • 1970-01-01
          • 2016-08-18
          相关资源
          最近更新 更多