【问题标题】:Java regex convert string to valid json stringJava 正则表达式将字符串转换为有效的 json 字符串
【发布时间】:2017-05-15 06:54:09
【问题描述】:

我有一个很长的字符串,看起来像

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

我想将其转换为有效的 json 字符串,例如

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

我开始查看字符串对象上的replaceAll(String regex, String replacement) 方法,但我正在努力为它找到正确的正则表达式。

谁能帮帮我。

【问题讨论】:

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

标签: java json regex string


【解决方案1】:

在这种特殊情况下,regex 应该查找以{space, 开头且后面不跟" 的单词

String str = "{abc:\"def\", ghi:\"jkl\"}";
String regex = "(?:[{ ,])(\\w+)(?!\")";
System.out.println(str.replaceAll(regex, "\\\"$1\\\""));

DEMOregex解释

【讨论】:

    【解决方案2】:

    我必须假设“键”和“值”仅包含 “单词字符”(\w),其中没有空格。

    这是我的程序。另请参阅 cmets in-line:

    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\"}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-16
      • 2016-12-03
      • 2012-01-28
      • 2022-11-18
      • 1970-01-01
      • 2018-04-06
      • 2013-06-09
      • 2015-09-09
      相关资源
      最近更新 更多