我正在尝试加入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()
出了什么问题?
答案 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文件。