You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python加载JSON数据时遇“expecting , delimiter”错误求助

Fixing the "expecting , delimiter" Error in Your JSON Parsing Code

Let's break down why you're hitting this error and fix your code step by step. The "expecting , delimiter" error typically points to invalid JSON syntax, but in your case, there are several code issues that are either causing syntax errors directly or leading to reading non-JSON content, which triggers the JSON parsing failure.

First, the obvious syntax error

Your line data = json.load(json_data...) has invalid Python syntax — those ellipses (...) aren't valid here. You need to pass just the file object directly to json.load().

Second, you're missing full file paths

When you collect textfiles.append(file), you're only storing the filename, not the full path to the file. Since os.walk traverses subfolders, trying to open path + filename will fail for files in subdirectories, leading to either a file-not-found error or reading the wrong content (if a duplicate filename exists in your root path). This broken file read is a common cause of JSON parsing errors.

Third, outdated Python 2 code

The lines reload(sys) and sys.setdefaultencoding('utf8') are Python 2-specific. If you're running this in Python 3 (which you should be), these lines will throw errors. Python 3 uses UTF-8 by default for string handling, so you don't need these at all.

Fourth, missing encoding when opening files

When opening text files containing JSON, it's best practice to specify the encoding (usually UTF-8) to avoid garbled text that could break JSON parsing.

Fixed Code

Here's the corrected version of your code with all these issues addressed:

import json
import os

# Replace with your actual root path
root_path = '/Users/.../'
textfiles = []

# Collect full paths to all .txt files
for root, dirs, files in os.walk(root_path):
    for file in files:
        if file.endswith(".txt"):
            # Get the full path to the file using os.path.join for cross-platform safety
            full_file_path = os.path.join(root, file)
            textfiles.append(full_file_path)

# Process each file with error handling
for file_path in textfiles:
    # Open the file with explicit UTF-8 encoding
    with open(file_path, 'r', encoding='utf-8') as json_data:
        try:
            data = json.load(json_data)
            # Add your logic to use the parsed data here
            print(f"Successfully parsed {file_path}")
        except json.JSONDecodeError as e:
            # Gracefully handle invalid JSON files and pinpoint the issue
            print(f"Error parsing {file_path}: {e}")

Key Changes Explained

  • Removed Python 2 cruft: Got rid of reload(sys) and sys.setdefaultencoding('utf8') since they're unnecessary and error-prone in Python 3.
  • Full file paths: Used os.path.join(root, file) to store complete file paths, ensuring you can open files correctly no matter which subfolder they're in.
  • Fixed json.load() syntax: Removed the invalid ellipses and passed the file object directly.
  • Specified encoding: Added encoding='utf-8' to open() to ensure consistent, correct reading of text files.
  • Added error handling: Wrapped the JSON parsing in a try/except block to catch and report specific decode errors, helping you quickly identify which files have invalid JSON syntax (if any).

If you still get the "expecting , delimiter" error after this, it means one of your .txt files actually contains invalid JSON. Use the error message's line/column number to inspect the problematic file and fix issues like missing commas, mismatched brackets, or unescaped quotes.

内容的提问来源于stack exchange,提问作者John Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:55:10