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

解析位置追踪APP文本文件时遇JSONDecodeError的解决咨询

解决JSON解析时的未终止字符串错误

问题出在你用split(' ')分割行内容的方式上:当WiFi名称包含空格(比如示例中的"Dublin Airport Free WiFi"),这个操作会把原本完整的JSON字符串拆成多个片段,你取dataparts[2]只能拿到JSON的开头部分,自然会触发JSONDecodeError。

修正方案

不要用空格分割,而是通过定位JSON的起始位置来拆分时间和数据部分,有两种可靠的实现方式:

方式1:通过查找JSON起始符号{拆分

这种方法不依赖固定长度,兼容性更强:

import json

InputFile = "你的文件路径.txt"
with open(InputFile, 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        
        # 找到JSON部分的起始位置
        json_start_idx = line.find('{')
        if json_start_idx == -1:
            print(f"跳过无效行:{line}")
            continue
        
        time_part = line[:json_start_idx].strip()
        json_content = line[json_start_idx:]
        
        try:
            geodata = json.loads(json_content)
            # 这里可以添加你的数据处理逻辑
            print(f"解析成功 | 时间: {time_part} | WiFi名称: {geodata['properties']['wifi']}")
        except json.JSONDecodeError as e:
            print(f"解析失败 | 错误信息: {e} | 行内容: {line}")

方式2:利用固定长度的时间前缀切片

观察到时间部分是固定格式YYYY-MM-DD HH:MM:SS.000000,总长度为26个字符,直接切片拆分:

import json

InputFile = "你的文件路径.txt"
with open(InputFile, 'r') as f:
    for line in f:
        line = line.strip()
        if len(line) < 26:
            continue
        
        time_part = line[:26].strip()
        json_content = line[26:].strip()
        
        try:
            geodata = json.loads(json_content)
            # 数据处理逻辑
            print(f"时间: {time_part} | WiFi: {geodata['properties']['wifi']}")
        except json.JSONDecodeError as e:
            print(f"解析错误: {e}")

额外建议

加上try-except捕获解析异常,可以避免单条错误行导致整个流程中断,方便你批量处理多个文件时排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:50:26