Python - JSON ValueError:额外数据

时间:2016-11-08 17:26:31

标签: python json

我正在尝试加入json个文件:

path_to_json = 'generated_playlists/p1/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

json文件的结构如下:

{"user1": {"Wild Wood": 1.0, "You Do Something To Me": 1.0, "Reprise": 1.0}}

但是当我这样做时:

for js in json_files:
    with open(os.path.join(path_to_json, js)) as json_file:
        pd_data = json.load(json_file)

我明白了:

ValueError: Extra data: line 1 column 145 - line 1 column 721 (char 144 - 720)

json.load()出了什么问题?

1 个答案:

答案 0 :(得分:2)

根据@edgarcosta的建议,您可以处理ValueError循环中try-except块中的for,如下所示:

import os
import json
import sys

path_to_json = 'generated_playlists/p1/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

for js in json_files:
    json_path = os.path.join(path_to_json, js)
    with open(json_path) as json_file:
        try:
            pd_data = json.load(json_file)
        except ValueError:
            sys.stderr.write('Could not parse JSON file: {0}'.format(json_path))

这可以帮助您识别无法读取哪些JSON文件。