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

如何将含逗号值的字符串正确转换为JSON格式

解决含逗号值的非标准JSON字符串转换问题

问题场景

现有一段非标准的类JSON字符串,其中body字段的值包含逗号,直接用replaceAll("=", ":")转换后,会导致body的值被错误分割,生成不符合预期的JSON:

原代码:

import com.jayway.jsonpath.JsonPath;

String strJSON = "{items=[{id=1647, address=sample, person=null, date=1686616249817, read=0, status=-1, type=1, subject=null, body=registration done successful, click on this to know more, serviceCenter=+910000000000}], total=1570}".replaceAll("=",":");
System.out.println(JsonPath.parse(strJSON).jsonString());

错误输出:

{"items":[{"id":1647,"address":"sample","person":null,"date":1686616249817,"read":0,"status":-1,"type":1,"subject":null,"body":"registration done successful","click on this to know more, serviceCenter":"+910000000000"}],"total":1570}

期望输出:

{"items":[{"id":1647,"address":"sample","person":null,"date":1686616249817,"read":0,"status":-1,"type":1,"subject":null,"body":"registration done successful,click on this to know more", "serviceCenter":"+910000000000"}],"total":1570}

解决方法

核心问题是原字符串未给字符串值添加引号,导致逗号被误判为键值对的分隔符。我们可以通过正则表达式精准匹配键值对,先为键和值添加引号,再修正数字、null等特殊值的格式:

import com.jayway.jsonpath.JsonPath;

public class JsonFixer {
    public static void main(String[] args) {
        String rawStr = "{items=[{id=1647, address=sample, person=null, date=1686616249817, read=0, status=-1, type=1, subject=null, body=registration done successful, click on this to know more, serviceCenter=+910000000000}], total=1570}";
        
        // 1. 匹配键值对:捕获键,捕获直到下一个", 键="或"}"的所有内容作为值,添加引号
        String quotedStr = rawStr.replaceAll("(\\w+)=((?:(?!,\\s*\\w+=|}).)*)", "\"$1\":\"$2\"");
        // 2. 移除null、数字的引号,符合JSON规范
        String validJson = quotedStr.replaceAll("\"(null|-?\\d+)\"", "$1");
        
        // 解析并输出标准JSON
        System.out.println(JsonPath.parse(validJson).jsonString());
    }
}

正则说明

  • 第一个正则(\\w+)=((?:(?!,\\s*\\w+=|}).)*):
    • (\\w+):匹配键名(字母、数字、下划线)
    • =:匹配键值分隔符
    • ((?:(?!,\\s*\\w+=|}).)*):非捕获组,匹配任意字符直到遇到, 键=(下一个键值对起始)或}(对象结束),确保完整捕获包含逗号的字段值
  • 第二个正则\"(null|-?\\d+)\":匹配被引号包裹的null或数字,替换为无引号的原始值,符合JSON语法规范

运行后即可得到符合预期的标准JSON输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:05:06