从 python 写入 json 文件时出现解析错误

Parsing errors when writing to a json file from python

我看到过类似的问题,但不确定我需要更改什么才能使其有效 json。 我有一个这样的字典列表:

dicts = [{'date': '2018-12-11',
  'target_currency': 'DKK',
  'exchange_rate': 7.4641,
  'base_currency': 'EUR'},
 {'date': '2018-12-11',
  'target_currency': 'GBP',
  'exchange_rate': 0.90228,
  'base_currency': 'EUR'},
...]

我已将其转换为 .json,如下所示:

        with open('cleaned.json', 'w') as f:
            for d in dict2:
                json.dump(d, f)
                f.write(',') 

https://jsonlint.com/ 上得到这个错误。

{
    "date": "2018-12-11",
    "target_currency": "USD",
    "exchange_rate": 1.1379,
    "base_currency": "EUR"
}, {
    "date": "2018-12-11",
    "target_currency": "JPY",
    "exchange_rate": 128.75,
    "base_currency": "EUR"
}, {
    "date": "2018-12-11",
    "target_currency": "BGN",
    "exchange_rate": 1.9558,
    "base_currency": "EUR"



Error: Parse error on line 6:
...e_currency": "EUR"}, {   "date": "2018-1
----------------------^
Expecting 'EOF', got ','

当我尝试更改新行分隔符 f.write('\n') 的逗号时,出现此错误:

Error: Parse error on line 6:
..._currency": "EUR"} { "date": "2018-12-
----------------------^
Expecting 'EOF', '}', ',', ']', got '{'

显然我正在错误地写入文件。我做错了什么?

我也试过用 with open('cleaned.jsonl', 'w') 和 [=34= 将它写成 .jsonl(json 行)格式]('\n')。 但我还有

JSONDecodeError: Extra data: line 2 column 1 (char 98)

当我使用 json.load() 再次加载它时。

import json

data = [{'date': '2018-12-11',
  'target_currency': 'DKK',
  'exchange_rate': 7.4641,
  'base_currency': 'EUR'},
 {'date': '2018-12-11',
  'target_currency': 'GBP',
  'exchange_rate': 0.90228,
  'base_currency': 'EUR'}]

with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)


with open('data.jsonl', 'w') as f:
    for item in data:
        f.write(json.dumps(item) + '\n')

输出data.json:

[
    {
        "date": "2018-12-11",
        "target_currency": "DKK",
        "exchange_rate": 7.4641,
        "base_currency": "EUR"
    },
    {
        "date": "2018-12-11",
        "target_currency": "GBP",
        "exchange_rate": 0.90228,
        "base_currency": "EUR"
    }
]

你可以用 json.load().

作为一个整体阅读

输出data.jsonl:

{"date": "2018-12-11", "target_currency": "DKK", "exchange_rate": 7.4641, "base_currency": "EUR"}
{"date": "2018-12-11", "target_currency": "GBP", "exchange_rate": 0.90228, "base_currency": "EUR"}

请注意ndjson/jsonl您不能将json模块作为一个文件来读取,您需要逐行read/parse。有第三方库可以方便地处理ndjson/jsonl。 此外,您无法在 https://jsonlint.com

上验证 ndjson/jsonl