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

如何将JSON文件中的NumberLong值转为字符串以修复合法性问题

修复JSON中NumberLong类型的非法格式问题

问题场景

你的JSON文件中存在NumberLong(数字)这种非标准JSON格式的值,例如:

{ 
    "display_url" : "bit.ly/1Thojq6", 
    "indices" : [ 
        90, 
        113 
    ] 
}, 
"user_mentions" : [], 
"symbols" : [], 
"media" : [ 
    { 
        "id" : NumberLong(715690140442734594), 
        "id_str" : "715690140442734594", 
        "indices" : [ 
            114, 
            137 
        ]
    }
]

这种格式不符合JSON规范,会导致解析失败,需要将NumberLong(xxx)包裹成字符串格式:

{ 
    "id" : "NumberLong(715690140442734594)", 
    "id_str" : "715690140442734594", 
    "indices" : [ 
        114, 
        137 
    ]
}

解决方法

1. 文本编辑器批量替换(快速处理单文件)

用支持正则查找替换的编辑器(如VS Code、Sublime Text、Notepad++)操作:

  • 查找正则:NumberLong\((\d+)\)
  • 替换为:"NumberLong($1)"

操作步骤:

  • 打开目标JSON文件
  • 调出查找替换面板(VS Code按Ctrl+Shift+H)
  • 勾选「使用正则表达式」选项
  • 输入上述查找和替换内容,点击「全部替换」

2. Python脚本批量处理(多文件/自动化场景)

如果需要处理大量文件或集成到工作流,用Python脚本实现:

import re
import json

def fix_numberlong(json_content):
    # 正则替换NumberLong格式为字符串
    fixed_content = re.sub(r'NumberLong\((\d+)\)', r'"NumberLong(\1)"', json_content)
    # 可选:验证修复后JSON合法性
    try:
        json.loads(fixed_content)
        print("修复后的JSON格式合法")
    except json.JSONDecodeError as e:
        print(f"修复后仍存在格式问题:{e}")
    return fixed_content

# 读取原文件
with open('your_file.json', 'r', encoding='utf-8') as f:
    content = f.read()

# 修复后保存新文件
fixed_content = fix_numberlong(content)
with open('fixed_file.json', 'w', encoding='utf-8') as f:
    f.write(fixed_content)

注意事项

  • 若存在带负号的NumberLong(-123)格式,可将正则调整为NumberLong\((-?\d+)\)
  • 处理前务必备份原文件,避免替换错误导致数据丢失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:40:19