在Python中处理巨大的json文件 - ValueError

时间:2016-01-06 18:53:04

标签: python json

我有这段代码用Python处理一个大文件:

import urllib2, json, csv
import requests

def readJson(url):
    """
    Read a json file.
    :param url: url to be read.
    :return: a json file.
    """
    try:
        response = urllib2.urlopen(url)
        return json.loads(response.read(), strict=False)
    except urllib2.HTTPError as e:
        return None

def getRoadsTopology():
    nodes = []
    edges = []

    url = "https://data.cityofnewyork.us/api/geospatial/svwp-sbcd?method=export&format=GeoJSON"
    data = readJson(url)
    print "Done reading road bed"
    print "Processing road bed..."

    v_index = 0;
    roads = 0
    for road in data['features']:
        n_index = len(nodes)
        # (long, lat)
        coordinates = road['geometry']['coordinates'][0]
        for i in range(0, len(coordinates)):
            lat_long = coordinates[i]
            nodes.append((lat_long[1], lat_long[0]))

        for i in range(n_index, len(nodes)-1-n_index):
            print i, i+1
            edges.append((i, i+1))
    return nodes, edges

有时它可以工作,但很多时候我在不同的行上得到同样的错误:

File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting : delimiter: line 7 column 4 (char 74317829)



File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 5 column 1 (char 72149996)

我想知道是什么导致了这些错误,并且在不同的行,以及我如何解决它。

提供此文件的网站也成功地展示了它:

https://data.cityofnewyork.us/City-Government/road/svwp-sbcd

1 个答案:

答案 0 :(得分:3)

看起来您的JSON输入格式不正确。该错误是从raw_decode抛出的,它是JSON库的一部分 - 所以它在转移到您的处理代码之前就会被转储。结果的不一致将导致我认为JSON可能以某种方式被破坏或未完全交付。

我的下一步是从源中提取JSON,存储在本地文件中,将其保存以确保它有效,然后直接从该文件测试您的程序。

<强>更新

好奇,我多次下载了这个文件。他们中的一些人太小了。看来实际尺寸大约是121M。一旦我得到了一些这些,我运行你的程序,用文件加载器替换你的url-loader。它工作得很好,除非我的RAM太少,然后产生一个段错误。

我在DigitalOcean上的虚拟服务器上下载文件最为成功 - 它每次都成功获得。在本地计算机上执行此操作时,该文件被截断,这使我相信可能发送给您JSON的服务器在一段超时时间后切断了流。 DigitalOcean服务器具有大容量吞吐量,平均12 MB / s,在10秒内拉动整个文件。我的本地机器只能拉不到1MB / s,无法完成。它停在2分钟,只有75Mb。发送服务器可能对请求有2分钟的时间限制。

这可以解释为什么他们的页面可以正常工作,但是你的脚本很难实现这一切。地图数据正由另一台服务器处理,该服务器可以在允许的时间内从源中提取数据,然后根据需要逐个流式传输到Web查看器。

相关问题