首页 > 解决方案 > 为什么这个 JSON 数据无效?

问题描述

我有以下从数据流调用生成的 JSON 文件。使用下面的代码,我无法打开文件,而是收到以下错误:

raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1

我使用 Jsonlint 并收到以下错误:

Expecting 'EOF', '}', ',', ']', got '{'

我试过通过熊猫打开文件,它也不起作用。任何帮助将不胜感激,我不确定如何调试。

from pprint import pprint

datajson = 'errortest.json'

with open(datajson) as f:
    data = json.load(f)

pprint(data)

输出:

{"target": {"icao_address": "A1AE05", "timestamp": "2019-10-27T22:25:55Z", "altitude_baro": 26000, "heading": 330.0, "speed": 389.9, "latitude": 34.636047, "longitude": -118.822127, "callsign": "SWA5282", "collection_type": "terrestrial", "ingestion_time": "2019-10-27T22:25:59Z", "tail_number": "N207WN", "icao_actype": "B737", "flight_number": "WN5282", "origin_airport_icao": "KLGB", "destination_airport_icao": "KOAK", "scheduled_departure_time_utc": "2019-10-27T22:05:00Z", "scheduled_departure_time_local": "2019-10-27T15:05:00", "scheduled_arrival_time_utc": "2019-10-27T23:20:00Z", "scheduled_arrival_time_local": "2019-10-27T16:20:00"}}
{"target": {"icao_address": "AB79DE", "timestamp": "2019-10-27T22:25:55Z", "altitude_baro": 30025, "heading": 260.0, "speed": 410.0, "latitude": 35.850716, "longitude": -101.077667, "callsign": "AAL2102", "collection_type": "terrestrial", "ingestion_time": "2019-10-27T22:25:59Z", "tail_number": "N839AW", "icao_actype": "A319", "flight_number": "AA2102", "origin_airport_icao": "KCMH", "destination_airport_icao": "KLAX", "scheduled_departure_time_utc": "2019-10-27T20:03:00Z", "scheduled_departure_time_local": "2019-10-27T16:03:00", "scheduled_arrival_time_utc": "2019-10-28T01:00:00Z", "scheduled_arrival_time_local": "2019-10-27T18:00:00", "estimated_arrival_time_utc": "2019-10-28T00:56:00Z", "estimated_arrival_time_local": "2019-10-27T17:56:00"}}

标签: pythonjsonpython-3.xfile

解决方案


那不是 JSON。那是一堆单独的 JSON 字符串,在不同的行上写入同一个文件。它通常被称为“JSON 行”,这种文件通常的、不太容易混淆的扩展名是.jsonl,而不是.json.

阅读各行并将它们传递给json.loads.


推荐阅读