视频加载失败

排查 sing-box 配置的语法与字段

sing-box 用 JSON 保存日志、DNS、入站、出站和路由配置。

读取失败时,先区分 JSON 语法提示与字段类型提示,例如 json: cannot unmarshal string into Go struct field 或 invalid character '}' looking for beginning of object key string。

先把文本解析通过,再检查字段、标签引用和路由。

sing-box 的 JSON 结构#

配置文件需符合 JSON 的语法要求。

  1. 在 {} 与 [] 内,最后一个成员后面都不加逗号。
  2. 键名和字符串用双引号包围,' 不能代替双引号。
  3. 写 Windows 路径 C:\Users\...\cache.db 时,要在 JSON 字符串里用 \\ 表示反斜杠。

各配置模块负责什么#

  1. log(日志):
    • 在 sing-box 中,level 控制日志级别。示例包括 trace、debug、info、warn、error、fatal。output 指定输出位置,排查时可临时查看 debug 日志。
  2. dns(域名解析):
    • 用 servers 定义解析器,rules 指定规则,final 处理未匹配项。若配置含 fakeip,还需核对相应写法。
  3. inbounds(入站):
    • 定义接收流量的方式,例如 tun、mixed、tproxy。
  4. outbounds(出站):
    • 用 tag 标识出站。例子包含 direct、block、selector、urltest。
  5. route(路由):
    • 通过 rules、rule_set 和 final 核对路由。使用 TUN 时,也可检查 auto_detect_interface。
  6. experimental(扩展):
    • sing-box 可通过 clash_api 连接 Clash 控制面板。先核对本机绑定和监听端口,如示例使用的 9090。

sing-box 加载配置时的 JSON 错误#

逗号、引号、转义和字段类型#

  1. 检查尾随逗号(Trailing Comma):
    • 在出站列表中检查末项之后有无逗号。
      // 错误示例: 最后一个大括号前多了一个逗号
      "outbounds": [
      { "type": "direct", "tag": "direct" },
      { "type": "block", "tag": "block" }, <-- 致命尾随逗号!
      ]
    • sing-box 的 encoding/json 若在 ] 附近返回 invalid character ']' looking for beginning of value,先检查列表末尾。
  2. 单引号和缺失的双引号:
    • 写成 'type': 'direct' 时,解析器可能返回 invalid character '\'' looking for beginning of object key string。给键名及字符串改用双引号。
  3. Windows 路径的转义:
    • 在 JSON 字符串中检查路径里的反斜杠是否已转义。
      // 错误写法: 单反斜杠被识别为非法转义序列
      "path": "C:UsersAdminsing-boxgeosite.db"
      // 正确合规写法: 使用双反斜杠进行严格转义, 或者直接使用标准正斜杠
      "path": "C:\\Users\\Admin\\sing-box\\geosite.db"
      "path": "C:/Users/Admin/sing-box/geosite.db"
  4. 字段类型不符(Type Mismatch):
    • 区分布尔值 "udp": true 和字符串 "udp": "true",也区分数字 "server_port": 443 与字符串 "server_port": "443"。若 json.Unmarshal 返回 json: cannot unmarshal string into Go struct field ... of type int,按提示定位到对应键。

sing-box 字段变化与迁移检查#

  1. 检查出站标签和列表名称:
    • 遇到 outbound 与 outbounds,按当前 sing-box 版本支持的字段名核对。
    • 用 tag 标识出站,在 outbounds 内确保没有重复的 tag。示例标签为 "tag": "proxy"。
  2. 配置规则集(Rule Set):
    • 旧配置若直接引用 geosite.db 或 geoip.db,应查运行中的 sing-box 支持的规则集写法。
    • route.rule_set
      "rule_set": [
      {
      "type": "remote",
      "tag": "geosite-geolocation-cn",
      "format": "binary",
      "url": "",
      "download_detour": "select-node"
      }
      ]
  3. 核对 route.final 的默认出站:
    • Clash 使用 MATCH,策略组 的位置和 sing-box 的 route 不同。在 sing-box 的路由配置中核对 final,例如 "final": "select-node"。
  4. TUN 模式下检查 auto_detect_interface:
    • 启用 tun 入站后,可在 route 对照 "auto_detect_interface": true 是否满足当前环境。
    • 启用 TUN 后,若连接又被送回 sing-box 的虚拟网卡,检查默认路由。

在 sing-box 中配置 clash_api#

需要 Clash 风格的控制面板时,可从 experimental 核对 sing-box 的扩展配置。

"experimental": {
"cache_file": {
"enabled": true,
"path": "cache.db",
"cache_id": "my_profile_cache"
},
"clash_api": {
"external_controller": "127.0.0.1:9090",
"external_ui": "ui",
"external_ui_download_url": "",
"external_ui_download_detour": "direct",
"secret": "MySuperSecretAdminToken123",
"default_mode": "rule"
}
}

控制面板连接排查#

  1. 检查 external_controller 的绑定地址,区分 127.0.0.1:9090 和 0.0.0.0:9090。
  2. 在 Linux 中开启 cache_file 后,可查看 sing-box 是否能写入保存位置,并检查 Fake-IP 缓存。

检查 sing-box JSON 的工具#

先检查文件语法,再由 sing-box 核对配置字段。

按检查目标选工具#

检查工具运行位置检查内容适合使用时机使用条件
sing-box 的 check 命令本地终端按 sing-box 的规则读取配置。定位字段名或配置加载错误。需要安装 sing-box。
jq命令行读取、解析和整理 JSON。核对结构或从 outbounds 提取 tag。sing-box 的配置字段与路由还需另行校验。
VS Code + JSON Schema文本编辑器利用 Schema 提示字段和数据类型。编辑配置时检查拼写和结构。先核对所用 Schema 是否对应当前版本。
JSONLint浏览器标出无法解析的 JSON 位置。检查引号和逗号等文本语法。敏感配置应在本机检查。

在终端运行 sing-box check 与 jq#

可在 Linux、路由器或本地终端执行配置检查。

用 sing-box 检查配置#

用 sing-box 的 check 读取指定文件,并查看返回的错误位置或字段。

Terminal window
# 1. 对指定的 JSON 配置文件执行静态合规性检查
sing-box check -c ./config.json
# 2. 如果配置完全合规无误,终端将直接静默退出 (返回退出码 0):
echo $?
# 输出: 0
# 3. 如果存在 JSON 语法错误 (例如存在尾随逗号),终端将给出极其精准的报错:
# fatal: read config: decode config/config.json: invalid character ']' looking for beginning of value at line 62, offset 1845
# 4. 如果存在未知字段或字段类型错误,终端将指出结构体映射失败:
# fatal: create service: json: unknown field "network" in struct type outbound.VLESSOptions

用 jq 提取出站标签#

先用 jq 读取 JSON,再按需列出出站标签。

Terminal window
# 1. 验证 JSON 语法完整性并以标准 2 空格美化高亮输出 (如果语法报错会当场拦截打印行号)
jq . config.json > config.formatted.json
# 2. 一键提取出站列表 (outbounds) 中定义的所有节点 tag 标签名称
jq -r '.outbounds[] | select(.tag != null) | .tag' config.json
# 3. 快速过滤出所有类型为 urltest 的策略组并检查其内部引用的出站节点
jq '.outbounds[] | select(.type == "urltest") | {tag: .tag, outbounds: .outbounds}' config.json

用 Python 检查 sing-box 配置的内部引用#

jq 能解析 JSON。还可用下方示例核对路由指向的标签是否在 outbounds 中。

#!/usr/bin/env python3
"""
生产级 sing-box JSON 配置文件全维度语法与业务逻辑完整性自检器
功能覆盖:
1. 严格检查 RFC 8259 JSON 格式, 精准捕获尾随逗号与引号异常行号
2. 提取 outbounds 全量可用 tag, 建立哈希索引池
3. 校验 selector 与 urltest 策略组内部引用的出站标签是否存在
4. 深度审查 route.rules 分流规则每一条指定的 outbound 是否合法
5. 验证 route.final 与 dns.final 兜底目标的有效性
"""
import sys
import json
import re
def validate_sing_box_config(config_path):
print("=" * 75)
print(f" 正在对 sing-box 配置文件发起严格语法与逻辑拓扑审计: {config_path}")
print("=" * 75)
# 1. 纯语法反序列化测试
try:
with open(config_path, 'r', encoding='utf-8') as f:
content = f.read()
data = json.loads(content)
except json.JSONDecodeError as err:
print(f"【严重语法错误】JSON 反序列化失败:
原因: {err.msg}
行号: 第 {err.lineno} 行, 列号: 第 {err.colno} 列")
# 提取出错行附近的文本上下文供排查
lines = content.splitlines()
start = max(0, err.lineno - 3)
end = min(len(lines), err.lineno + 2)
print(" 上下文代码片段:")
for idx in range(start, end):
prefix = ">> " if idx + 1 == err.lineno else " "
print(f" {prefix}{idx + 1:03d} | {lines[idx]}")
print("=" * 75)
return False
except Exception as err:
print(f"【读取异常】文件无法正常打开: {err}")
print("=" * 75)
return False
if not isinstance(data, dict):
print("【错误】根结构必须为标准 JSON 对象 (大括号包裹的字典)!")
return False
# 2. 核心顶级模块存在性检查
core_modules = ["inbounds", "outbounds", "route"]
for m in core_modules:
if m not in data:
print(f"【严重警告】配置中缺失核心顶级模块: '{m}'")
raw_inbounds = data.get("inbounds", []) or []
raw_outbounds = data.get("outbounds", []) or []
route_obj = data.get("route", {}) or {}
dns_obj = data.get("dns", {}) or {}
# 3. 建立出站 tag 标签池与系统保留标签池
outbound_tags = set()
builtin_tags = {"direct", "block", "dns-out"}
duplicate_tags = set()
for ob in raw_outbounds:
if isinstance(ob, dict) and "tag" in ob:
t = ob["tag"]
if t in outbound_tags:
duplicate_tags.add(t)
outbound_tags.add(t)
all_valid_outbounds = outbound_tags | builtin_tags
print(f"[*] 模块统计: 入站数 = {len(raw_inbounds)} | 出站节点数 = {len(outbound_tags)} | 路由规则数 = {len(route_obj.get('rules', []))}")
print("-" * 75)
error_count = 0
# 检查是否有重名 tag
if duplicate_tags:
for dt in duplicate_tags:
print(f" [严重标签冲突] outbounds 中存在重名标签: '{dt}'")
error_count += 1
# 4. 审查策略组 (selector / urltest) 内部引用完整性
for ob in raw_outbounds:
ob_type = ob.get("type", "")
ob_tag = ob.get("tag", "未命名出站")
if ob_type in ["selector", "urltest"]:
child_outbounds = ob.get("outbounds", []) or []
if not child_outbounds:
print(f" [逻辑空载] 策略组【{ob_tag}】未配置任何子出站节点 (outbounds 列表为空)!")
error_count += 1
for cot in child_outbounds:
if cot not in all_valid_outbounds:
print(f" [引用缺失] 策略组【{ob_tag}】引用了不存在的出站标签: '{cot}'")
error_count += 1
# 5. 校验 route 路由模块配置
route_final = route_obj.get("final")
if not route_final:
print(" [路由隐患] route 模块缺失 'final' 兜底出站声明!未命中规则的流量将被丢弃!")
error_count += 1
elif route_final not in all_valid_outbounds:
print(f" [致命路由错误] route.final 指向了不存在的出站: '{route_final}'")
error_count += 1
# 检查 route.rules
route_rules = route_obj.get("rules", []) or []
for r_idx, rule in enumerate(route_rules, 1):
if not isinstance(rule, dict):
continue
# 兼容 outbound 与 action
rule_target = rule.get("outbound")
rule_action = rule.get("action")
if rule_target and rule_target not in all_valid_outbounds:
print(f" [规则目标无效] route.rules 规则 #{r_idx} 指定的 outbound 不存在: '{rule_target}'")
error_count += 1
# 6. 校验 DNS 模块 final 兜底
dns_servers = dns_obj.get("servers", []) or []
dns_server_tags = {s.get("tag") for s in dns_servers if isinstance(s, dict) and "tag" in s}
dns_final = dns_obj.get("final")
if dns_final and dns_final not in dns_server_tags:
print(f" [DNS 错误] dns.final 指向了未定义的 DNS 服务器标签: '{dns_final}'")
error_count += 1
print("-" * 75)
if error_count == 0:
print("【全量验收 PASS】sing-box 配置文件语法完备, 依赖拓扑闭环, 无任何逻辑死锁!")
print("=" * 75)
return True
else:
print(f"【验收失败 FAIL】共捕获到 {error_count} 处严重结构与引用缺陷, 请修正后再启动!")
print("=" * 75)
return False
if __name__ == "__main__":
target_config = sys.argv[1] if len(sys.argv) > 1 else "config.json"
validate_sing_box_config(target_config)

sing-box JSON 配置示例#

套用 TUN 配置示例前,核对本机 sing-box 版本所接受的字段。

{
"log": {
"disabled": false,
"level": "info",
"timestamp": true
},
"dns": {
"servers": [
{
"tag": "dns-remote",
"address": "",
"address_resolver": "dns-direct",
"strategy": "prefer_ipv4",
"detour": "proxy"
},
{
"tag": "dns-direct",
"address": "223.5.5.5",
"address_resolver": "dns-local",
"strategy": "prefer_ipv4",
"detour": "direct"
},
{
"tag": "dns-local",
"address": "local",
"detour": "direct"
},
{
"tag": "dns-block",
"address": "rcode://success"
}
],
"rules": [
{
"outbound": "any",
"server": "dns-direct"
},
{
"rule_set": "geosite-cn",
"server": "dns-direct"
}
],
"final": "dns-remote",
"strategy": "prefer_ipv4"
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"interface_name": "singbox-tun",
"inet4_address": "172.19.0.1/30",
"auto_route": true,
"strict_route": true,
"stack": "system",
"sniff": true
},
{
"type": "mixed",
"tag": "mixed-in",
"listen": "127.0.0.1",
"listen_port": 2080
}
],
"outbounds": [
{
"type": "selector",
"tag": "proxy",
"outbounds": [
"auto-fast",
"hk-node-01",
"direct"
],
"default": "auto-fast"
},
{
"type": "urltest",
"tag": "auto-fast",
"outbounds": [
"hk-node-01"
],
"url": "",
"interval": "3m",
"tolerance": 50
},
{
"type": "shadowsocks",
"tag": "hk-node-01",
"server": "hk01.example.com",
"server_port": 8443,
"method": "2022-blake3-aes-128-gcm",
"password": "SecurePasswordBlake3_123"
},
{
"type": "direct",
"tag": "direct"
},
{
"type": "block",
"tag": "block"
},
{
"type": "dns",
"tag": "dns-out"
}
],
"route": {
"auto_detect_interface": true,
"rules": [
{
"protocol": "dns",
"outbound": "dns-out"
},
{
"ip_is_private": true,
"outbound": "direct"
},
{
"rule_set": "geosite-cn",
"outbound": "direct"
},
{
"rule_set": "geoip-cn",
"outbound": "direct"
}
],
"rule_set": [
{
"type": "remote",
"tag": "geosite-cn",
"format": "binary",
"url": "",
"download_detour": "direct"
},
{
"type": "remote",
"tag": "geoip-cn",
"format": "binary",
"url": "",
"download_detour": "direct"
}
],
"final": "proxy"
}
}

TUN 网卡的协议栈选项#

stack 决定 sing-box 的 TUN 使用哪种协议栈。

system、gvisor 与 mixed#

  1. system(操作系统协议栈):
    • 通过 Linux 或 Windows 的原生协议栈处理数据包。
  2. gvisor(Google 开源的用户态协议栈):
    • 在 sing-box 中,这项设置使用用户态网络栈处理 TCP/IP 数据。
  3. mixed(混合协议栈):
    • 排查时可对照 system 和 stack 的配置,再和 gvisor 的实际表现比较。

TUN 的路径与 MTU#

TUN 的 mtu 设置要结合实际链路的封装和可承载的包大小。

  1. 对照 MTU 设置
    • 使用 Hysteria2、TUIC、WireGuard 或 PPPoE 接入时,可检查封装前后的包大小与重传。
    • 若启用 TUN 后短请求正常而传大文件停顿,可对照调整 MTU 前后的结果。inbounds.tun
      "mtu": 1400
Terminal window
systemctl status sing-box
sing-box.service: Main process exited, code=exited, status=1/FAILURE
Dec 08 14:10:02 gateway sing-box[18241]: fatal error: read config: decode config.json: invalid character ']' looking for beginning of value at line 89, offset 2614
{
"type": "direct",
"tag": "direct"
}, <-- 后面没有其他节点了,但末尾保留了逗号!
]
Terminal window
netstat -rn
Terminal window
sing-box run -c config.json
panic: unexpected EOF reading binary rule-set
goroutine 1 [running]:
github.com/sagernet/sing-box/common/srs.Read(...)
Terminal window
ls -lh /var/lib/sing-box/
# 发现 geosite-cn.srs 的文件大小竟然是 0 字节!
"route": {
"rules": [
{ "rule_set": "geosite-cn", "outbound": "direct" },
{ "rule_set": "geosite-google", "outbound": "proxy-hk" }
]
}
"final": "proxy-hk"

常见问题#

JSON 格式正确,为什么 sing-box 仍不接受?#

通用工具只能检查 JSON 文本。还需查看 outbounds 是否为数组,核对出站类型是 shadowsocks、vless,还是误写成了 v-less,再用 sing-box check 检查。

sing-box 的 rule_set 有哪些读取方式?#

  • 设为 type: remote 时,sing-box 引用 GitHub 或 CDN 等远端托管的规则集。
  • 设为 type: local 时,规则集从本机读取,例如 .srs 或 .json 文件。

sing-box 的 JSON 文件可以写注释吗?#

按 RFC 8259 的 JSON 语法,// 和 /* ... */ 都不属于合法的标准 JSON 注释写法。检查 sing-box 文件时可先移除这些注释。

Terminal window
# 1. 在重载前,务必先执行静态测试确保新配置百分之百合法!
sing-box check -c /etc/sing-box/config.json
# 2. 向正在运行的 sing-box 守护进程发送 SIGHUP 信号触发热重载
sudo systemctl reload sing-box
# 或者直接向进程 PID 发送信号:
sudo kill -HUP $(pgrep sing-box)

相关网络技术专题#

文章分享

排查 sing-box 配置的语法与字段
许可协议
CC BY-NC-SA 4.0
随机文章随机推荐
jcwangping.co
网络加速线路、客户端设置与连接故障排查。
分类
按标签浏览
站点信息
构建平台
Cloudflare Pages
文章许可
CC BY-NC-SA 4.0
文章目录