Java正则表达式将字符串转换为有效的JSON字符串

3

我有一个相当长的字符串,看起来像这样

{abc:\"def\", ghi:\"jkl\"}

我想将这个转换成有效的JSON字符串,例如:
{\"abc\":\"def\", \"ghi\":\"jkl\"}

我开始研究字符串对象上的replaceAll(String regex, String replacement)方法,但我无法找到正确的正则表达式。

能有人帮我吗?


2
另一种方法是使用宽松解析器进行解析,例如Gson提供了一个setLenient()方法。然后将其重新写回为有效的JSON格式。 - Andreas
你正在使用哪个JSON依赖项?更好的选择是根据正确的格式生成它,无论是客户端还是服务器端。 - Pavneet_Singh
你可以尝试通过搜索由标识符字符序列后跟 : 进行替换,但如果值字符串中有冒号,则可能会失败。其他可能会使您失败的事情是在其中一个值内部存在转义引号。可能可以想出一个处理所有内容的复杂正则表达式,但在这种情况下,最好编写自己的词法分析器来处理输入中的标记(如 {:,、标识符、字符串文字)并从中工作。过于复杂的正则表达式难以阅读且容易出错。 - ajb
2个回答

2
您IP地址为146.190.162.183,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。
String str = "{abc:\"def\", ghi:\"jkl\"}";
String regex = "(?:[{ ,])(\\w+)(?!\")";
System.out.println(str.replaceAll(regex, "\\\"$1\\\""));

演示正则表达式 解释


0

我必须假设“键”和“值”仅由“单词字符”(\w)组成,并且它们中没有空格。

这是我的程序。请同时查看内联注释:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexJson {

    public static void main(String[] args) {
        /*
         * Note that the input string, when expressed in a Java program, need escape
         * for backslash (\) and double quote (").  If you read directly
         * from a file then these escapes are not needed
         */
        String input = "{abc:\\\"def\\\", ghi:\\\"jkl\\\"}";

        // regex for one pair of key-value pair.  Eg: abc:\"edf\"
        String keyValueRegex = "(?<key>\\w+):(?<value>\\\\\\\"\\w+\\\\\\\")";
        // regex for a list of key-value pair, separated by a comma (,) and a space ( )
        String pairsRegex    = "(?<pairs>(,*\\s*"+keyValueRegex+")+)";
        // regex include the open and closing braces ({})
        String regex         = "\\{"+pairsRegex+"\\}";

        StringBuilder sb = new StringBuilder();

        sb.append("{");
        Pattern p1 = Pattern.compile(regex);
        Matcher m1 = p1.matcher(input);
        while (m1.find()) {
            String pairs = m1.group("pairs");
            Pattern p2 = Pattern.compile(keyValueRegex);
            Matcher m2 = p2.matcher(pairs);
            String comma = "";      // first time special
            while (m2.find()) {
                String key      = m2.group("key");
                String value    = m2.group("value");
                sb.append(String.format(comma + "\\\"%s\\\":%s", key, value));
                comma = ", ";       // second time and onwards
            }
        }
        sb.append("}");

        System.out.println("input is: " + input);
        System.out.println(sb.toString());
    }

}

这个程序的输出结果是:

input is: {abc:\"def\", ghi:\"jkl\"}
{\"abc\":\"def\", \"ghi\":\"jkl\"}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接